Running time for a video question
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?
Open Chat in New Window