We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Days Between Two Dates

Number: 1274

Difficulty: Easy

Paid? No

Companies: Amazon, Microsoft, Optiver, Accenture


Problem Description

Write a program to count the number of days between two valid dates provided in the format YYYY-MM-DD.


Key Insights

  • Convert date strings into year, month, and day components.
  • Calculate the total number of days since a fixed reference point (e.g., January 1, 1971) for each date.
  • Use the helper function to account for leap years and the varying number of days in each month.
  • Return the absolute difference between the total days of the two dates.

Space and Time Complexity

Time Complexity: O(1) - The calculation involves a fixed number of operations regardless of the input. Space Complexity: O(1) - Only a constant amount of extra space is utilized.


Solution

The key idea of the solution is to convert each date into a count of days from a fixed reference date (January 1, 1971). This is achieved by summing:

  1. The number of days for each full year since the reference year.
  2. The number of days for the complete months of the current year (taking leap years into account).
  3. The days in the current month. Once both dates are converted into total day counts, the absolute difference between these counts gives the number of days between the dates.

The approach efficiently handles the varying lengths of months and leap years within the given constraints.


Code Solutions

# Python solution
def daysBetweenDates(date1: str, date2: str) -> int:
    # Determine if the given year is a leap year
    def is_leap_year(year: int) -> bool:
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
    
    # Days in each month for non-leap years
    month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    # Convert a date string 'YYYY-MM-DD' to days since 1971-01-01
    def date_to_days(date: str) -> int:
        year, month, day = map(int, date.split('-'))
        days = 0
        # Sum days for complete years from 1971 up to the year before the current year
        for y in range(1971, year):
            days += 366 if is_leap_year(y) else 365
        # Sum days for complete months in the current year
        for m in range(1, month):
            if m == 2 and is_leap_year(year):
                days += 29
            else:
                days += month_days[m - 1]
        # Add days in the current month
        days += day
        return days

    # Calculate and return the absolute difference between the two dates in days
    return abs(date_to_days(date1) - date_to_days(date2))

# Example usage:
print(daysBetweenDates("2019-06-29", "2019-06-30"))
← Back to All Questions