Maximum Population Year — LeetCode 1854 Python Solution
- Problem
- #1854
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- logs = [[1993,1999],[2000,2010]]
- Output
- 1993
- Explanation
- The maximum population is 1, and 1993 is the earliest year with this population.
Python solution
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
d = [0] * 101
offset = 1950
for a, b in logs:
a, b = a - offset, b - offset
d[a] += 1
d[b] -= 1
s = mx = j = 0
for i, x in enumerate(d):
s += x
if mx < s:
mx, j = s, i
return j + offsetComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1854. Maximum Population Year is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1854. Maximum Population Year?
- LeetCode 1854. Maximum Population Year is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1854. Maximum Population Year?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1854. Maximum Population Year?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 1854. Maximum Population Year cover?
- LeetCode 1854. Maximum Population Year is tagged Array, Counting and Prefix Sum on LeetCode.