KatInterview

Gap in Days Between Two Calendar Strings Without Date Libraries

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationdate-arithmeticleap-yearstring-parsing

Last updated

Parse two ISO-style date strings and compute the absolute day gap using manual Gregorian leap-year logic, without any date or calendar library.

Gap in Days Between Two Calendar Strings

Two calendar dates arrive as text in the form YYYY-MM-DD. Work out how many days separate them and return that count as a non-negative integer.

Your solution must not use any built-in date, time, or calendar facility (for example Python's datetime or calendar modules). All calendar logic has to come from the rules below, which you implement yourself.

Calendar rules

  • Month lengths are: January 31, February 28 (29 in a leap year), March 31, April 30, May 31, June 30, July 31, August 31, September 30, October 31, November 30, December 31.
  • A year is a leap year if it is divisible by 4, except when it is divisible by 100, unless it is also divisible by 400. Thus 2000 and 2024 are leap years, while 1900 and 2100 are not.

Input

  • first_date: a string in YYYY-MM-DD format.
  • second_date: a string in YYYY-MM-DD format.

Both strings are valid calendar dates. Either one may be the earlier date.

Output

Return one integer: the absolute number of days between the two dates. If both dates are identical, return 0.

Constraints

  • 1900-01-01 <= first_date, second_date <= 2100-12-31
  • Both inputs are valid dates written exactly as YYYY-MM-DD.
  • No date/time library may be used; leap years must be handled using the rules above.

Examples

Example 1

Input: day_gap('2019-06-29', '2019-06-30')

Output: 1

Example 2

Input: day_gap('2019-12-31', '2020-01-15')

Output: 15

Example 3

Input: day_gap('2020-02-28', '2020-03-01')

Output: 2

Example 4

Input: day_gap('2019-02-28', '2019-03-01')

Output: 1

Example 5

Input: day_gap('2021-07-04', '2021-07-04')

Output: 0

Hints

Hint 1

Instead of subtracting year, month and day separately, think about turning each date into a single number: how many days have passed since some fixed starting point.

Hint 2

The starting point cancels out when you subtract, so pick whichever is convenient. For a date Y-M-D, add up the days in all complete years before Y, the days in the complete months before M, and then D - 1.

Hint 3

Count leap years before year Y with n = Y - 1: n // 4 - n // 100 + n // 400. Add the leap day for February only when the month is after February and Y itself is a leap year. Finish with abs().