Running time for a video question

Forum Post 0 Answers Running time for a video question

Hi all,
On one of the video Gayle presents the following problem -
"Given p number of people with their birth year and their death year, return the year with the maximum population".

At the same video she also states the best possible solution is O(P+Y) s.t. P is the number of peoples and Y is the length of the array of the years from the minimal birth year to the maximal death year, Can't the optimal solution be O(P)?

Here's how -
Generally she achieved a solution of O(P+Y) since she iterate through all the peoples in the input getting the minimal year and the maximal year that is O(P) which gives her Y the total number of years all the people was living in, then she instantiate an array on the size of Y that is O(Y), then she goes through every person in the input, add +1 for birth and -1 for deaths so that is O(P) and lastly she goes through all the array of years summing up the number of +1\-1 to that point which is giving her the number of people living in that year so again O(Y), all together it's O(P+Y+P+Y) => O(P+Y)

However - using a TreeMap (a hashmap that uses an inner tree to sort the dataset) we can achieve O(P), here's how -
traverse the people input and for every person p on the people list add +1 for the person birth year and -1 for the person death year that will end up with a tree with total (MAX) of 2*p nodes and traversing the tree to every year can yield that same result as traversing an array on the size of Y (however using a tree with 2p nodes is much memory efficient than using an array with potentially a-lot of unused 0's) while traversing the tree we can also keep int max which is the year with the max alive people in it.

Isn't that a better solution? or am I missing something?

- iosdevresume July 13, 2018 | Flag |

Add a Comment

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.


is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More


CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More