Solution: Third Maximum Number
Let’s solve the Third Maximum Number problem using the Top K Elements pattern.
We'll cover the following
Statement
For a given integer array nums
, your task is to return the third maximum distinct number in the array. If there are fewer than three distinct numbers, return the maximum number.
Constraints:
nums.length
nums[i]
Solution
The solution uses a min heap to track the list’s top three maximum numbers. A set ensures that only distinct numbers are considered. The approach keeps a rolling set of the top three numbers, updating it as larger numbers are encountered and ensuring no duplicates are included.
Now, let’s walk through the steps of the solution:
We create a min heap,
heap
, to store the top three distinct numbers.We also create a set,
taken
to store numbers that have already been added to the heap, ensuring we only push distinct numbers into the heap.We iterate through the
nums
list, and for each element in the list, we check if it has already been added to thetaken
set:If it has, we skip that element.
If it hasn’t, we proceed to check the length of the heap:
If the heap has less than three numbers, we push the current number into the heap and add it to the
taken
set.If the heap already contains three numbers and the current number is larger than the smallest number in the heap (the root of the heap), we remove the smallest number, update the
taken
set, and push the current number into the heap.
We also handle special cases where the list has fewer than three distinct numbers:
After processing all the numbers, we check the size of the heap:
If the heap contains only one number, we return that number since it’s the only distinct maximum.
If the heap contains two distinct numbers, we return the larger of the two.
If the heap contains three distinct numbers, we return the smallest number from the heap, which will be the third maximum distinct number.
Let’s look at the following illustration to get a better understanding:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.