File: maximum-population-year/solution.py

Date: 2026-06-06

Time: 17:41

maximum-population-year/solution.py

Purpose

This file solves LeetCode 1854 — Maximum Population Year. It determines the earliest year in which the most people are simultaneously alive, given a list of [birth, death] pairs where a person is alive during [birth, death-1] (i.e., death year is exclusive).

Key Components

maxAliveYear(logs: list[list[int]]) -> int — The sole public function. Takes a list of birth/death pairs and returns the earliest year with peak population.

Patterns

Difference array (sweep line): Instead of incrementing every year a person is alive (O(n * range)), the solution records only boundary events — +1 at birth, -1 at death — then reconstructs population via prefix sum. This is a standard O(n + range) technique for range-increment queries.

The year range is hardcoded to [1950, 2050] per the problem constraints, making the delta array a fixed 101 elements. The offset - 1950 maps calendar years to zero-based indices.

Dependencies

Imports: None. Pure algorithmic code with no external dependencies.

Imported by: The test_solution.py file in the same directory imports this function. The "Imported By" list in the prompt is misleading — those are unrelated test files that happen to share a test harness pattern, not actual consumers of this function.

Flow

1. Build delta array: For each person [birth, death], increment delta[birth - 1950] and decrement delta[death - 1950]. The decrement at death (not death - 1) is correct because the person is alive only through death - 1.

2. Prefix-sum scan: Walk delta left to right, accumulating running. At each index, if running > maxpop, update maxpop and best_year.

3. Return best_year.

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints. An empty logs list returns 1950 (the initial bestyear value with maxpop = 0), which is arguably wrong but matches LeetCode's constraint that logs is non-empty.