~/problems / Simulation & OOP design / Simulation

Days between two dates (no datetime)

easy ~20 min Optiver

Write days_between(a: str, b: str) -> int. Both arguments are dates in the form "YYYY-MM-DD" (always zero-padded, always a real date) in the proleptic Gregorian calendar, with years from 0001 to 9999. Return the absolute number of days separating them, so the answer is 0 when they are equal and the order of the arguments doesn't matter.

Do the calendar arithmetic yourself. Don't import datetime, calendar, time or any other date library; the tests check that your file doesn't mention them. (The tests themselves use datetime as the reference answer.)

Things to get right:

  • Month lengths: 31, 28/29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.
  • Leap years: divisible by 4, except centuries, except centuries divisible by 400. So 2000 and 2400 are leap years, 1900 and 2100 are not.
  • The whole year range. Walking one day (or one year) at a time is too slow for the performance test; convert each date to a day number with a closed formula and subtract.
days_between("2011-01-03", "2011-01-05")   # 2
days_between("2020-03-01", "2020-02-28")   # 2   (2020 is a leap year)
days_between("1900-03-01", "1900-02-28")   # 1   (1900 is not)
days_between("0001-01-01", "9999-12-31")   # 3652058

Topic: Simulation. Model the process exactly; watch simultaneous updates and direction arithmetic.

0:00
Ctrl ' run · Ctrl ↵ submit
esc