Difficulty: Easy | Acceptance: 52.70% | Paid: No Topics: Math, String
Write a program to count the number of days between two dates.
The dates are given as strings, their format is YYYY-MM-DD as shown in the example.
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
- Examples
- Constraints
- Approach 1: Built-in Libraries
- Approach 2: Manual Calculation (Julian Day)
- Approach 3: Brute Force Iteration
Examples
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
Constraints
- The given dates are valid dates between the years 1971 and 2100.
Approach 1: Built-in Libraries
Intuition Most modern programming languages provide robust date and time libraries that handle leap years, varying month lengths, and date arithmetic automatically. We can leverage these to parse the strings and calculate the difference directly.
Steps
- Parse the input strings into date objects using the standard library for the language.
- Calculate the absolute difference between the two dates in days.
- Return the result.
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
import datetime
d1 = datetime.datetime.strptime(date1, "%Y-%m-%d").date()
d2 = datetime.datetime.strptime(date2, "%Y-%m-%d").date()
return abs((d2 - d1).days)Complexity
- Time: O(1)
- Space: O(1)
- Notes: Relies on standard library implementations which are highly optimized.
Approach 2: Manual Calculation (Julian Day)
Intuition We can convert each date into a “Julian Day Number” (the number of days elapsed since a fixed reference point, like 1971-01-01). The difference between these two numbers is the answer. This requires manually handling leap years and days in months.
Steps
- Define a helper function to check if a year is a leap year.
- Define a helper function to calculate the total days from 1971-01-01 to the given date.
- Sum the days for all years from 1971 to the current year - 1.
- Sum the days for all months from January to the current month - 1.
- Add the day of the month.
- Return the absolute difference between the day counts of the two dates.
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
def is_leap(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
def days_from_1971(date):
y, m, d = map(int, date.split('-'))
days = 0
for year in range(1971, y):
days += 366 if is_leap(year) else 365
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap(y):
month_days[1] = 29
for month in range(1, m):
days += month_days[month - 1]
days += d
return days
return abs(days_from_1971(date1) - days_from_1971(date2))Complexity
- Time: O(1) (The loop iterates over a maximum of ~130 years, which is constant).
- Space: O(1)
- Notes: Avoids library overhead, requires careful implementation of leap year logic.
Approach 3: Brute Force Iteration
Intuition Starting from the earlier date, we can increment the date by one day at a time until we reach the later date, counting the steps. This is simple but less efficient for large gaps.
Steps
- Parse the dates into year, month, and day integers.
- Determine which date is earlier.
- While the earlier date is not equal to the later date:
- Increment the day.
- Handle month and year rollovers (e.g., if day exceeds days in month, reset day to 1 and increment month).
- Increment the counter.
- Return the counter.
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
import datetime
d1 = datetime.datetime.strptime(date1, "%Y-%m-%d").date()
d2 = datetime.datetime.strptime(date2, "%Y-%m-%d").date()
if d1 > d2:
d1, d2 = d2, d1
count = 0
while d1 < d2:
d1 += datetime.timedelta(days=1)
count += 1
return countComplexity
- Time: O(N), where N is the number of days between the two dates.
- Space: O(1)
- Notes: Simple to implement but inefficient for large date ranges compared to O(1) methods.