Finding the maximum value in an array is trivial, but what about the third distinct maximum? "Third Maximum Number" asks you to find the third-largest unique number in an array. If there are fewer than three distinct numbers, the problem typically asks you to return the maximum number instead.
This Third Maximum Number interview question is a classic "easy" problem asked by top companies like Apple, Microsoft, and Google. It tests your ability to handle distinctness and track multiple variables simultaneously. While sorting is an easy way to solve it, interviewers often look for a linear O(n) solution to see if you can avoid the O(n log n) cost of a full sort.
This problem follows the Array, Sorting interview pattern.
first, second, third) initialized to a value smaller than any possible input (or use null/None). Iterate through the array once:
first, shift all three variables down.second, shift second and third down.third, update third.third if it was updated, else return first.Array: [3, 2, 2, 1]
In "Third Maximum Number coding problem," many candidates forget to handle duplicate numbers, incorrectly returning the third element of a sorted list even if it's a repeat of the second. Another error is not correctly handling the "return the max if no third max exists" rule. Using a value like Integer.MIN_VALUE for initialization can also be risky if that value is actually present in the input array.
When tracking the "top K" elements of an array, always consider if you need a full sort or just a fixed set of variables. For small K (like 3), variables are much more efficient. For larger K, a min-heap is the standard tool. Always be clear about whether you are dealing with "distinct" values or not.