Date: 2026-06-06
Time: 17:41
maximum-population-year/solution.pyThis 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).
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.
delta: A 101-element array representing the year range 1950–2050. Each index maps to a year via index + 1950. Acts as a difference array where +1 marks a birth and -1 marks a death.running: Prefix-sum accumulator that reconstructs the actual population at each year from the delta array.maxpop / bestyear: Track the maximum population seen so far and the corresponding year. Because the scan is left-to-right, the earliest year wins ties naturally.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.
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.
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.
1950 <= birth < death <= 2050. The delta array is sized exactly for this range. Out-of-range inputs would cause an index error.> comparison guarantees the earliest year wins when multiple years share the same peak population.delta[death - 1950] -= 1 correctly models the person not being alive in their death year. If you mistakenly used death - 1, you'd undercount the population drop by one year.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.