Handling ranges: Prefix sum + frequency array
Course: Intro Class 2- DSA - chapter 6
Often we are given problems around ranges. Let’s take this problem: https://leetcode.com/problems/maximum-population-year/description/
Essentially what do we want here? What is the year when maximum number of people are living.
The brute force solution can be:
1. Iterate through all the possible years2. For an year, iterate through the list of ranges and see if the person is alive for that year. If yes, add 1 to the count.3. Update the ans to count if greaterHow can we optimise this? Think of this problem as range intersection, basically given a list of ranges, what is the maximum number of ranges that are intersecting at a point.
One way to solve it is using sorting the ranges and then iterating. However, we will do a better approach.
Let’s say we maintain a frequency array for the years, where freq[i] = number of people alive in year i.
To populate this array we can do something like:
freq[2051] = {0}
for [birth, death] in persons { for (year -> birth to death) freq[year] += 1}Now we can easily use the freq array to find the answer which is the index at which freq is maximum.
But can we optimise this further? Yes!
Think it like the altitude problem: For each year, we can have a gain[year] value, which is what is the gain / loss in population for this year.
If we have gain[year], calculating freq is simple right? Just do prefix sum! (Same logic as maximum altitude, where we found total altitude at every point using prefix sum)
Now how to calculate gain efficiently? Well, iterate through all the ranges and gain[birth] += 1, gain[death] -= 1. Because, when someone is born, we are gaining by 1, but when someone dies, we lose by 1.
Final solution
Section titled “Final solution”Steps:1. Calculate gain array 1.1 Create a gain array with all 0 initially 1.2 Loop over all birth/death pairs. For each birth, death pair, add +1 in gain for birth and -1 in gain for death2. Calculate prefix sum to find the freq of number of people alive every year3. Calculate the index where frequency is maximum