Problem Description
Given a list of logs where each log represents the birth and death years of a person, determine the earliest year with the maximum number of people alive. A person is considered alive in the inclusive range [birth, death-1] (i.e., they are not counted in the year of their death).
Key Insights
- Use a difference array (or prefix sum technique) to mark changes in population over the years.
- Increment the population counter at the birth year and decrement at the death year.
- Traverse through the years (from 1950 to 2050) to compute the prefix sum, which gives the population for each year.
- Track the maximum population and update the earliest year whenever a new maximum is found.
Space and Time Complexity
Time Complexity: O(R) where R is the range of years (a constant range from 1950 to 2050, so effectively O(1)). Space Complexity: O(R) for the difference array (again constant space with respect to input size).
Solution
We use a difference array technique to track the population changes. For each log, we increase the population count at the birth year and decrease it at the death year (since the person is not alive during the death year). We then iterate through the years from 1950 to 2050, accumulating the changes to compute the population per year. By tracking the maximum population encountered and choosing the earliest year with that population, we can determine the required answer.