Calculate Days Between Arbitrary Gregorian Dates
OptiverSoftware Engineer · Online AssessmentLast updated
This problem tests the ability to implement a calendar-based calculation algorithm, specifically handling leap year logic and modular arithmetic without iterating through every day.
Problem Description
Write a function days_between(date1, date2) that returns the absolute number of days between two Gregorian dates. Each date is represented as a tuple or list: (year, month, day).
Rules
- A year is a leap year if it is divisible by 4, except for years divisible by 100 that are not divisible by 400.
- You must not iterate day-by-day. Your solution should ideally run in O(1) time complexity relative to the distance between dates.
- Years can be as large as 10,000,000.
Function Signature
def days_between(date1: tuple, date2: tuple) -> int:
# date = (year, month, day)
Example
# Input: (2020, 1, 1), (2021, 1, 1)
# Output: 366
# Explanation: 2020 was a leap year.
# Input: (2000, 1, 1), (2001, 1, 1)
# Output: 366
# Explanation: 2000 is divisible by 400, thus a leap year.
Constraints
- 1 <= year <= 10^7
- 1 <= month <= 12
- 1 <= day <= days_in_month(month, year)
Edge Cases
- Leap years at the turn of the century (e.g., 1900 vs 2000).
- Same date inputs (should return 0).
- Dates in the same year/same month.
Hints
Hint 1
Convert each date into a total count of days elapsed from a fixed reference point, such as 0001-01-01.
Hint 2
Calculate the number of leap years up to a given year using the formula: (year // 4) - (year // 100) + (year // 400).
Hint 3
Remember to handle the current year's month and day offset carefully, ensuring you only count full months completed in the current year.
Follow-up questions
- How would your approach change if you had to account for historical calendar switches, such as the transition from the Julian to the Gregorian calendar in 1582?
- If you were to store these dates in a database, would you store them as strings, integers (seconds since epoch), or custom objects? What are the pros and cons?
- How would you modify your solution to support timezone offsets or daylight saving time transitions?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.