Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Number of Days Between Two Dates

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1360" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples. Example 1: Input: date1 = "2019-06-29", date2 = "2019-06-30" Output: 1 Example 2: Input: date1 = "2020-01-15", date2 = "2019-12-31" Output: 15 Constraints: The given dates are valid dates between the years 1971 and 2100.

Explanation

Here's the breakdown of the approach, complexity, and the Python code:

  • High-Level Approach:

    • Convert both date strings into a total number of days since a fixed reference date (e.g., 1970-12-31).
    • Calculate the absolute difference between these two day counts.
    • Return the absolute difference.
  • Complexity:

    • Runtime Complexity: O(1) - because the date range is limited (1971-2100), the number of operations is bounded and doesn't scale with input size.
    • Storage Complexity: O(1) - uses a fixed amount of memory regardless of the input dates.

Code

    def daysBetweenDates(date1: str, date2: str) -> int:
    """
    Calculates the number of days between two dates.

    Args:
        date1: The first date string in YYYY-MM-DD format.
        date2: The second date string in YYYY-MM-DD format.

    Returns:
        The absolute number of days between the two dates.
    """

    def days_from_19701231(date: str) -> int:
        year, month, day = map(int, date.split('-'))
        days = 0
        for y in range(1970, year):
            days += 365
            if is_leap_year(y):
                days += 1

        days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if is_leap_year(year):
            days_in_month[2] = 29

        for m in range(1, month):
            days += days_in_month[m]

        days += day

        # Adjust because our base is 1970-12-31 and not 1970-01-01
        days -= 365  # Remove days for 1970

        return days

    def is_leap_year(year: int) -> bool:
        return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

    days1 = days_from_19701231(date1)
    days2 = days_from_19701231(date2)
    return abs(days1 - days2)

More from this blog

C

Chatmagic blog

2894 posts