Maximum Population Year
Core idea: You're given a list of people as
[birth, death]pairs, where a person is alive during the yearsbirth โค year < death(death is exclusive โ the year of death does not count). You want the earliest year in which the most people are simultaneously alive. The naive move is to walk every year and recount everyone โ wasteful, because the alive-count only changes at births and deaths. So instead you mark a difference array:+1at each birth year,โ1at each death year. A single left-to-right prefix sum over the years turns those deltas into the running population, and you track the max and the earliest year that hit it. That's a line sweep: O(years + n) time, O(years) space.
The problem, rephrased
A census office hands you a stack of life records. Each record is a pair logs[i] = [birth_i, death_i]: the person is counted as alive in every year y with birth_i โค y < death_i. (So someone born in 1950 who dies in 1961 is alive in 1950, 1951, โฆ, 1960 โ not 1961.) Return the earliest year that has the maximum population. If several years tie for the peak, return the smallest of them.
This is LeetCode 1854 โ Maximum Population Year. The constraint that makes line sweep shine: years are bounded to 1950 โค birth < death โค 2050.
Input logs |
What it means | Output |
|---|---|---|
[[1993,1999],[2000,2010]] |
two non-overlapping lives; peak is 1 person | 1993 |
[[1950,1961],[1960,1971],[1970,1981]] |
overlaps at 1960 and 1970, each with 2 alive | 1960 |
[[2008,2026],[2004,2008],[2034,2035],[1999,2010],[2031,2034],[2022,2034],[2018,2027],[1993,2009]] |
a messier overlap | 2004 |
The function returns a single integer โ the earliest peak year.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson