Days Between Two Calendar Dates
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
You are given two dates as strings, each in the format YYYY-MM-DD. Write a function that returns the number of days between the two dates as a non-negative integer (i.e., the absolute difference).
You must account for the varying lengths of months and for leap years. Do not rely on built-in date/calendar libraries — implement the calendar arithmetic yourself. A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years unless they are also divisible by 400 (so 2000 and 2020 are leap years, but 1900 and 2100 are not). In a leap year, February has 29 days; otherwise it has 28.
date1
: a string in the format
YYYY-MM-DD
date2
: a string in the format
YYYY-MM-DD
Both strings are guaranteed to be well-formed, valid calendar dates. The dates may be given in either order (date1 may be before, after, or equal to date2).
Return a single integer: the absolute number of days between the two dates. Two equal dates have a difference of 0.
Example 1
Input: date1 = "2019-12-31", date2 = "2020-01-15"
Output: 15
From December 31, 2019 to January 15, 2020 is 15 days.
Example 2
Input: date1 = "2020-03-01", date2 = "2020-02-28"
Output: 2
2020 is a leap year, so February 29, 2020 exists: February 28 → February 29 → March 1 is 2 days.
Example 3
Input: date1 = "2021-02-28", date2 = "2021-03-01"
Output: 1
2021 is not a leap year, so February 28 is immediately followed by March 1.
Example 4
Input: date1 = "2020-05-05", date2 = "2020-05-05"
Output: 0
1900-01-01
and
2100-12-31
inclusive.