Calculate Day Count Between Two Dates
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Tests understanding of calendar arithmetic including leap year logic, month lengths, and converting dates to a numeric representation.
Calculate Day Count Between Two Dates
Write a function that computes how many days separate two given dates. Each date is provided as a string in YYYY-MM-DD format, and your function should return the absolute difference as a non-negative integer.
Important: Implement the calendar logic yourself without using built-in date or calendar libraries. You must handle leap years and varying month lengths correctly.
Leap Year Rules
A year is a leap year if:
- It is divisible by 4, except
- Years divisible by 100 are not leap years, unless
- They are also divisible by 400
Examples: 2000 and 2020 are leap years. 1900 and 2100 are not.
In leap years, February has 29 days. In non-leap years, February has 28 days.
Input
date1: A string representing a valid date inYYYY-MM-DDformatdate2: A string representing a valid date inYYYY-MM-DDformat
The dates may be in any order (either date could be earlier or later).
Output
Return an integer representing the absolute number of days between the two dates. If the dates are identical, return 0.
Constraints
- Both dates are valid calendar dates between
1900-01-01and2100-12-31inclusive - The result will fit in a 32-bit signed integer
- Input strings are well-formed and represent valid dates
Examples
Example 1
Input: calculate_day_difference('2019-12-31', '2020-01-15')
Output: 15
Example 2
Input: calculate_day_difference('2020-03-01', '2020-02-28')
Output: 2
Example 3
Input: calculate_day_difference('2021-02-28', '2021-03-01')
Output: 1
Example 4
Input: calculate_day_difference('2020-05-05', '2020-05-05')
Output: 0
Hints
Hint 1
Convert each date into a single number representing days from a fixed reference point, then find the absolute difference
Hint 2
Count total days in all complete years before the target year using a formula that accounts for leap years
Hint 3
Use inclusion-exclusion: count multiples of 4, subtract multiples of 100, add back multiples of 400
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to map each date to a single integer representing the number of days since a fixed reference point. Once both dates are converted to these ordinal values, the answer is simply the absolute difference between them.
For a date with components (year, month, day), the ordinal is computed in three parts:
-
Days in all complete years before the current year (years 1 through
year - 1):- Base days:
365 × (year - 1) - Additional leap days:
(year - 1) // 4 - (year - 1) // 100 + (year - 1) // 400
- Base days:
-
Days in all complete months of the current year (months before
month):- Sum the lengths of months 1 through
month - 1 - February's length depends on whether the current year is a leap year
- Sum the lengths of months 1 through
-
The day of the month: simply add
day
The leap year counting formula uses inclusion-exclusion:
y // 4counts all years divisible by 4- Subtract
y // 100to remove century years - Add back
y // 400to restore centuries that are leap years
This produces a strictly monotonic mapping where consecutive calendar days map to consecutive integers, making the difference equal to the day count.
Why It Works
Since ordinals increase by exactly 1 for each calendar day, the difference between two ordinals equals the number of days between those dates. Using absolute value handles input order automatically.
The formula correctly handles all edge cases:
- Year boundaries work seamlessly because the year component absorbs them
- Leap years are identified correctly including century rules
- February length uses the current year's leap status
- Equal dates produce identical ordinals, giving difference 0
Complexity
Time: O(1) — Parsing the date string is constant time, computing the year term is arithmetic, and summing month lengths iterates at most 11 elements.
Space: O(1) — Only a fixed-size month length array and a few integer variables are needed.
Solution
def calculate_day_difference(date1: str, date2: str) -> int:
def is_leap(year: int) -> bool:
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
def to_ordinal(date: str) -> int:
year, month, day = map(int, date.split('-'))
days_before_year = 365 * (year - 1) + (year - 1) // 4 - (year - 1) // 100 + (year - 1) // 400
month_lengths = [31, 29 if is_leap(year) else 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31]
return days_before_year + sum(month_lengths[:month - 1]) + day
return abs(to_ordinal(date1) - to_ordinal(date2))