# The Calendar Sort

> Time has its own opinion about order.

Canonical URL: <https://datadriven.io/problems/the_calendar_sort>

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.

## 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

**Lexicographic sort exploiting ISO date format**

```python
def sort_dates(dates):
    result = sorted(dates)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n log n) for the sort.
> 
> **Space:** O(n) for the sorted copy.

> **Interviewers Watch For**
>
> The insight that no date parsing is needed. Candidates who import datetime or manually split on hyphens are overcomplicating it.

> **Common Pitfall**
>
> Parsing dates when simple string sort works. The YYYY-MM-DD format is specifically designed for lexicographic ordering. Using a date library adds unnecessary complexity.

---

## Common 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.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_calendar_sort)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.