Number of Days Between Two Dates Problem
Description
LeetCode Problem 1360.
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
1971and2100.
Solution
Approach: Count Days from a Fixed Start
Subtracting two dates field by field gets messy (borrowing across months of different lengths and across leap years). It is much simpler to turn each date into a single number, the days since a fixed start date, and subtract those. All dates are from 1971 on, so count from 1971-01-01:
- Add the length of every full year from 1971 up to (not including) the date's year: 366 for a leap year, 365 otherwise.
- Add the lengths of the full months before the date's month, in the date's own year.
- Add
day - 1for the days already passed in the current month.
The answer is the absolute difference of the two counts, since date1 may be after date2 (Example 2).
The tricky part is the leap-year rule: a year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if also divisible by 400. In the given range this matters: 2000 is a leap year, but 2100 is not. February has 29 days in a leap year and 28 otherwise.
Complexity: O(Y) time, where Y is the number of years since 1971 (at most 130), plus 12 months, so effectively O(1); O(1) space.
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
return abs(self.daysSince1971(date1) - self.daysSince1971(date2))
def isLeap(self, year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def daysSince1971(self, date: str) -> int:
"""Days from 1971-01-01 to date (1971-01-01 itself gives 0)."""
year, month, day = map(int, date.split("-"))
month_days = [31, 29 if self.isLeap(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = sum(366 if self.isLeap(y) else 365 for y in range(1971, year))
days += sum(month_days[: month - 1])
return days + day - 1