KatInterview

Count Days Between Two Dates

Math & Bit ManipulationAuto-graded · 22 test cases
MediumAuto-gradedMath & Bit Manipulationmathcalendarmodular-arithmetic

Last updated

Tests efficient calendar arithmetic by computing date intervals without iteration, requiring leap year logic and modular reasoning.

Compute the absolute difference in days between two dates in the Gregorian calendar. Each date is provided as a list or tuple containing three integers: [year, month, day].

Your implementation must run in constant time relative to the span between dates—you cannot loop through each individual day or year. The input may include years up to 10,000,000.

Leap Year Rules

A year qualifies as a leap year when:

  • It is evenly divisible by 4, AND
  • Either it is not evenly divisible by 100, OR it is evenly divisible by 400.

Examples: 2000 and 2020 are leap years. 1900 and 2100 are not.

Constraints

  • 1 ≤ year ≤ 10^7
  • 1 ≤ month ≤ 12
  • 1 ≤ day ≤ valid day count for the given month and year
  • All inputs represent valid Gregorian calendar dates
  • Return the non-negative difference regardless of argument order

Examples

Example 1

Input: days_between([2020, 1, 1], [2021, 1, 1])

Output: 366

Example 2

Input: days_between([2000, 1, 1], [2001, 1, 1])

Output: 366

Example 3

Input: days_between([2021, 1, 1], [2020, 1, 1])

Output: 366

Example 4

Input: days_between([2020, 2, 28], [2020, 3, 1])

Output: 2

Hints

Hint 1

Convert each date into a single integer representing days since a fixed starting point, then find the absolute difference between these integers.

Hint 2

Count days contributed by complete years before the target year using inclusion-exclusion for leap years: add multiples of 4, subtract multiples of 100, add back multiples of 400.

Hint 3

For months within the current year, use cumulative day counts. Remember to add one extra day if the date falls after February in a leap year.