KatInterview

Calculate Day Count Between Two Dates

Math & Bit ManipulationAuto-graded · 23 test cases
MediumAuto-gradedMath & Bit Manipulationmathimplementationdate-arithmetic

Last 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 in YYYY-MM-DD format
  • date2: A string representing a valid date in YYYY-MM-DD format

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-01 and 2100-12-31 inclusive
  • 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