Maximum Population Year - Problem
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] represents the birth and death years of the i-th person.
Your task is to find the earliest year that had the maximum population. The population in any year x is the count of people who were alive during that year.
Important: A person is considered alive from their birth year up to (but not including) their death year. For example, if someone was born in 1950 and died in 1961, they contribute to the population count for years 1950-1960, but not 1961.
Goal: Return the earliest year with the maximum population count.
Input & Output
example_1.py โ Basic Case
$
Input:
logs = [[1993,1999],[2000,2010]]
โบ
Output:
1993
๐ก Note:
Person 1 lives from 1993-1998, Person 2 lives from 2000-2009. No overlap, so earliest birth year 1993 has population 1, which equals the maximum.
example_2.py โ Overlapping Lives
$
Input:
logs = [[1950,1961],[1960,1971],[1970,1981]]
โบ
Output:
1960
๐ก Note:
Person 1: 1950-1960, Person 2: 1960-1970, Person 3: 1970-1980. Year 1960 has 2 people alive (Person 1 still alive, Person 2 just born), which is the maximum.
example_3.py โ Multiple Peak Years
$
Input:
logs = [[2008,2026],[2004,2008],[2034,2035],[1999,2050]]
โบ
Output:
2004
๐ก Note:
Multiple years have population 2, but we return the earliest: 2004 (Person 2 + Person 4 alive).
Constraints
- 1 โค logs.length โค 100
- 1950 โค birthi < deathi โค 2050
- Person dies in deathi year, so not counted in that year's population
Visualization
Tap to expand
Understanding the Visualization
1
Record Events
Mark all check-ins (+1) and check-outs (-1)
2
Sort Timeline
Process events in chronological order
3
Track Running Total
Calculate occupancy at each time point
4
Find Peak
Identify maximum occupancy and its earliest occurrence
Key Takeaway
๐ฏ Key Insight: Instead of checking every year individually, we only track population change events and use prefix sums to efficiently calculate the maximum population.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code