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.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= logs.length <= 1001950 <= birthi < deathi <= 2050
Solution
Method 1 - Track the max pop
To solve the problem:
- Observation:
- Each person contributes to population from their birth year (
birthi) to one year before their death (deathi - 1). - To efficiently compute populations across years, we can utilise a difference array approach.
- Each person contributes to population from their birth year (
- Approach:
- Step 1: Initialise an array (
population) large enough to encompass all possible years, assuming a bounded range of years. - Step 2: For each person:
- Increment the population for
birthi. - Decrement the population for
deathi(marking the end of their contribution).
- Increment the population for
- Step 3: Perform a prefix sum over the population array to calculate the population for individual years.
- Step 4: Iterate over the population array to identify the year with the maximum population. If there are ties, select the earliest year.
- Step 1: Initialise an array (
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + R):O(n)to process all logs to update the difference array.O(R)for prefix sum and finding maximum population, whereRis the range of years.
- 🧺 Space complexity:
O(R):- Array size corresponds to the number of years covered (usually within range
[1950, 2050]).
- Array size corresponds to the number of years covered (usually within range