Given a list of people with their birth and end years (all between 1900
and 2000
), find the year with the most number of people alive.
Here
I would go like this:
unborn
list)alive
listalive
list that dies first, remove it from the list.alive
list in a dictunborn
and alive
lists are emptyComplexity should be around O((m + n) * log(m))
(each year is considered only once, and each person only twice, multiplied by the insertion cost in the alive
list)
from bisect import insort
def most_populated(population, single=True):
years = dict()
unborn = sorted(population, key=lambda x: -x[0])
alive = []
dead = []
for year in range(unborn[-1][0], max(population, key=lambda x: x[1])[1] + 1):
while unborn and unborn[-1][0] == year:
insort(alive, -unborn.pop()[1])
while alive and alive[-1] == -(year - 1):
dead.append(-alive.pop())
years[year] = len(alive)
return max(years, key=years.get) if single else \
[key for key, val in years.iteritems() if val == max(years.values())]