Maximum Population Year
You are given a list of logs where each log [birth, death] indicates a person born in birth and died in death. Population in a year is the number of people alive in that year. A person is counted in year x if birth <= x < death (not including death year). Find the earliest year with the maximum population.
The years range from 1950 to 2050 (101 years). Use a difference array of size 101: for each person, increment at birth-1950 and decrement at death-1950. Then compute prefix sums to get population at each year. Track the year with max population.
This is a classic prefix sum / difference array DP problem. The O(n) prefix sum over a fixed range gives O(n) time overall. Edge cases include all people in the same year range or a single person.
The difference array technique (marking birth and death years) combined with prefix sums efficiently computes population per year without iterating each year per person. This O(n + 101) approach works well for the fixed 101-year range from 1950 to 2050.
The difference array marks population changes at specific years. Each birth adds a person (+1) and each death removes one (-1). After building this array, a single prefix sum scan computes the actual population for each of the 101 years, and we track the year with the maximum population.
Example Input & Output
Single person born 2000.
Single person born 1950.
Both alive 1985-1989, max=2 at 1985.
1960: persons 1&2 alive=2.
1993: person1 alive=1; 2000: person2 alive=1. Earliest max=1993.
Algorithm Flow

Solution Approach
Create diff[101], for each log: diff[birth-1950]++, diff[death-1950]--. Prefix sum over diff, track max.
Time O(n), Space O(1) fixed 101.
Best Answers
class Solution {
public int solution(int[][] logs) {
int[] years = new int[101];
for (int[] l : logs) {
years[l[0] - 1950]++;
if (l[1] < 2050) years[l[1] - 1950]--;
}
int maxPop = 0, cur = 0, best = 1950;
for (int i = 0; i < 101; i++) {
cur += years[i];
if (cur > maxPop) { maxPop = cur; best = 1950 + i; }
}
return best;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
