The Calendar Sort
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a list of date strings 'YYYY-MM-DD', return them sorted chronologically ascending. Since ISO format sorts correctly as strings, a lexicographic sort works. Do not use date libraries.
Time has its own opinion about order.
Example
Input:
dates = ["2024-03-15","2023-01-01","2024-01-01"]
Output:
["2023-01-01","2024-01-01","2024-03-15"]
Worked solution and explanation
Why this problem exists in real interviews
Sorting date strings lexicographically tests the insight that YYYY-MM-DD format sorts correctly as strings. No date parsing is needed because the format is already year-major.
Break down the requirements
Step 1: Recognize that ISO date format sorts lexicographically
The YYYY-MM-DD format is designed so that string comparison matches chronological order.
Step 2: Sort the list of strings
A standard string sort produces the correct chronological order.
The solution
def sort_dates(dates):
result = sorted(dates)
return resultCommon follow-up questions
- What if the dates were in MM/DD/YYYY format? (Tests parsing to a comparable format before sorting, since month-first does not sort correctly as strings.)
- What if some dates have single-digit months without zero-padding? (Tests that `'2024-1-15'` sorts incorrectly vs. `'2024-01-15'` and requires normalization.)
- How would you sort dates with timestamps? (Tests that ISO 8601 with `T` separator also sorts correctly as strings.)