Maximum Population Year - Problem

You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.

The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.

Return the earliest year with the maximum population.

Input & Output

Example 1 — Basic Case
$ Input: logs = [[1993,1999],[2000,2010]]
Output: 1993
💡 Note: Person 1 lived from 1993-1998 (not counting 1999). Person 2 lived from 2000-2009. Each year has population 1, so return earliest year 1993.
Example 2 — Overlapping Lives
$ Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
Output: 1960
💡 Note: Years 1960-1970 have 2 people alive (persons 1&2 overlap in 1960, persons 2&3 overlap in 1970). Return earliest year with max population: 1960.
Example 3 — Single Person
$ Input: logs = [[2000,2050]]
Output: 2000
💡 Note: Only one person alive from 2000-2049. Population is 1 for all these years, return earliest: 2000.

Constraints

  • 1 ≤ logs.length ≤ 100
  • 1950 ≤ birthi < deathi ≤ 2050

Visualization

Tap to expand
Maximum Population Year INPUT logs = [[1993,1999],[2000,2010]] Person 1 Birth: 1993 Death: 1999 Person 2 Birth: 2000 Death: 2010 Timeline: 1993 1999 2000 2010 P1 P2 ALGORITHM STEPS 1 Create Delta Array Mark +1 at birth, -1 at death 2 Apply Line Sweep Process events chronologically 3 Compute Prefix Sum Running total = population 4 Find Max Year Return earliest max pop year Delta Array Changes: Year Delta Pop 1993 +1 1 1999 -1 0 2000 +1 1 2010 -1 0 FINAL RESULT Maximum Population Year 1993 Population = 1 Person 1 alive in 1993 Earliest year with max pop Output: 1993 OK Key Insight: Use Line Sweep with delta array: +1 at birth year, -1 at death year. Compute prefix sum to get population at each year. Return earliest year with maximum population. Time: O(n + range), Space: O(range) TutorialsPoint - Maximum Population Year | Optimal Solution (Line Sweep)
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen