Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Date Difference From Scratch

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Date Difference From Scratch. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Apple Health may contain events recorded on different calendar dates. Given two valid dates in the proleptic Gregorian calendar, calculate the exact absolute difference in days without using standard library date parsers or date classes.

Implement days_between(date1, date2). Each date is a string in YYYY-MM-DD format. Parse the components manually, account for leap years, and return the non-negative number of days between the dates. A Gregorian leap year is divisible by 4, except century years must also be divisible by 400.

Formal Specification

  • Input: Two strings, date1 and date2, each formatted as YYYY-MM-DD.
  • Output: An integer representing the absolute number of calendar days between the dates.
  • Dates use years from 1 through 9999 and are guaranteed to be valid.
  • Do not use datetime, date parsers, timestamps, or external libraries.

Constraints

  • 1 <= year <= 9999
  • Dates are valid in the proleptic Gregorian calendar
  • Each date has the exact format YYYY-MM-DD
  • The result fits in a Python integer

Function Signature

def days_between(date1, date2):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output