Count the Days Between Two 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 calendar dates as strings in YYYY-MM-DD format. Return the number of days between them as a non-negative integer.
You must compute the result without using any built-in date/time or calendar library (e.g., no datetime, java.time, Date, or similar). The only calendar knowledge you may rely on is the standard Gregorian calendar rules given below. Assume a helper that returns the number of days in a given month is something you write yourself.
date1
: a string in
YYYY-MM-DD
format.
date2
: a string in
YYYY-MM-DD
format.
Both dates are guaranteed to be valid calendar dates between 1900-01-01 and 2100-12-31 inclusive. The dates may be given in either order (date1 is not necessarily earlier than date2).
Return a single integer: the absolute difference in days between the two dates. If the dates are equal, return 0.
| date1 | date2 | Output | Explanation |
|---|---|---|---|
2019-06-29 | 2019-06-30 | 1 | Consecutive days. |
2019-12-31 | 2020-01-15 | 15 | Crosses a year boundary. |
2020-02-28 | 2020-03-01 | 2 | 2020 is a leap year, so February 29 lies between them. |
2019-02-28 | 2019-03-01 | 1 | 2019 is not a leap year. |
2021-07-04 | 2021-07-04 | 0 | Same date. |
1900-01-01 <= date1, date2 <= 2100-12-31
YYYY-MM-DD
format.