progress

~/problems / Simulation & OOP design / Simulation

Days between two dates (no datetime)

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Optiver

Write days_between(a: str, b: str) -> int. Both are real dates "YYYY-MM-DD" (zero-padded, years 0001 to 9999, proleptic Gregorian calendar). Return the absolute number of days between them (0 if equal).

Do the calendar arithmetic yourself: don't import datetime, calendar, time or any other date library (the tests check your file).

  • 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 (2000 is leap, 1900 is not).
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

⭐ Bonus: walking one day or one year at a time still passes; a speed test with 20,000 date pairs about 10,000 years apart earns a star if you turn each date into a day number with a closed formula and subtract.

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

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc