Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum population year using Python
Given a table with birth and death years of people, we need to find the earliest year with the maximum population. A person is counted as alive during year y if y is in the range [birth, death - 1] (they are not counted in their death year).
For example, with the following data:
| Birth | Death |
|---|---|
| 1970 | 2010 |
| 1960 | 2020 |
| 1940 | 1970 |
We need to find the year when the most people were alive simultaneously.
Algorithm
We will use a dictionary to count the population for each year:
- Create a dictionary to store year-wise population count
- For each person, increment the count for every year they were alive
- Track the maximum population and the earliest year with that population
- Return the earliest year with maximum population
Implementation
from collections import defaultdict
def find_max_population_year(matrix):
population_count = defaultdict(int)
max_population_year = [2051, 0] # [year, population]
for birth_year, death_year in matrix:
for year in range(birth_year, death_year):
population_count[year] += 1
if population_count[year] >= max_population_year[1]:
if population_count[year] > max_population_year[1]:
max_population_year = [year, population_count[year]]
else:
# If same population, choose earlier year
max_population_year = [min(year, max_population_year[0]), max_population_year[1]]
return max_population_year[0]
# Test with example data
birth_death_data = [[1970, 2010], [1960, 2020], [1940, 1970]]
result = find_max_population_year(birth_death_data)
print(f"Year with maximum population: {result}")
Year with maximum population: 1960
How It Works
Let's trace through the example:
- Person 1 (1970-2010): Alive during years 1970-2009
- Person 2 (1960-2020): Alive during years 1960-2019
- Person 3 (1940-1970): Alive during years 1940-1969
The overlapping years and their populations:
- 1940-1959: 1 person (Person 3)
- 1960-1969: 2 people (Person 2 and Person 3)
- 1970-2009: 2 people (Person 1 and Person 2)
- 2010-2019: 1 person (Person 2)
The maximum population is 2, occurring first in year 1960.
Time and Space Complexity
- Time Complexity: O(n × m) where n is number of people and m is average lifespan
- Space Complexity: O(y) where y is the number of unique years covered
Conclusion
This solution efficiently finds the earliest year with maximum population by counting people alive in each year. The algorithm ensures we get the earliest year when multiple years have the same maximum population.
