#1854

Maximum Population Year

Easy
ArrayCountingPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking each year individually, we can use a counting array to track population changes at birth and death years. This allows us to efficiently compute the population for each year in a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create an array to count population changes for each year from 1950 to 2050.
  2. 2Step 2: For each log entry, increment the birth year and decrement the death year in the counting array.
  3. 3Step 3: Iterate through the counting array to calculate the running population and track the maximum population and the earliest year.
solution.py14 lines
1def maximumPopulation(logs):
2    population_changes = [0] * 102
3    for birth, death in logs:
4        population_changes[birth - 1950] += 1
5        population_changes[death - 1950] -= 1
6    max_population = 0
7    current_population = 0
8    year_with_max_population = 0
9    for year in range(102):
10        current_population += population_changes[year]
11        if current_population > max_population:
12            max_population = current_population
13            year_with_max_population = year + 1950
14    return year_with_max_population

Complexity note: This complexity is O(n) because we only pass through the logs once to set up the population changes and then through the years once to calculate the population, making it efficient.

  • 1Population changes can be tracked using a counting array.
  • 2The earliest year with maximum population can be found efficiently using a single pass.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.