AlgoInsight

DSA problem

Maximum Population Year

EasyPrefix SumPattern: Difference Arraytop600Amazon

You are given a 2D integer array logs where each logs[i] = [birth_i, death_i] 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 [birth_i, death_i - 1]. Note that the person is not counted in the year that they die.

Return the earliest year with the maximum population.

This is a difference-array problem: instead of incrementing every year of a person's lifespan, mark +1 at the birth year and -1 at the death year, then take a running sum to recover the population per year.

Examples

Example 1
Input: logs = [[1993,1999],[2000,2010]]
Output: 1993
Explanation: The years with maximum population are 1993 to 1998 and 2000 to 2009 — all with population 1. The earliest such year is 1993.
Example 2
Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
Output: 1960
Explanation: The maximum population is 2, achieved in the year range 1960 to 1960. The earliest year is 1960.
Example 3
Input: logs = [[2008,2026],[2004,2008],[2008,2026]]
Output: 2008
Explanation: In 2008 the first and third persons are alive (the second person dies in 2008 and is not counted), giving a population of 2 — the maximum.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

prefix-sumdifference-arrayarraycounting

Browse all DSA problems