easy

Third Maximum Number

Find the third distinct largest number in an array.

1. Define the problem

Third Maximum Number

Given an integer array nums, return the third distinct maximum number in this array. If the third distinct maximum does not exist, return the maximum number. Track three variables — first, second, and third — in a single pass , updating them as you scan so the largest, second largest, and third largest distinct values are always up to date.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -231 ≤ numsi ≤ 231 - 1

Example

Inputnums = [3, 2, 1]
Output1

Explanation The distinct maximums are 3, 2, then 1 — the third maximum is 1.

2. Visualize the solution

Track the top three distinct values in one pass

Track the top three distinct values in one pass
Statusinit

value=3. No trackers set yet, so first=3.

What happens in this step

value = nums[0] = 3
first, second, third are all unset

3 becomes first.
Step 1 of 4

Steps to visualize

  1. Keep three trackers: first, second, and third, all starting as "not set".
  2. For each number, skip it if it equals a tracker already holding that exact value.
  3. If it is bigger than first, shift first down to second, second down to third, and this becomes first.
  4. Otherwise place it into second or third similarly if it fits between the current trackers.
  5. At the end, return third if it was set, otherwise return first.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Track the top three distinct values in one pass
Statusinit

value=3. No trackers set yet, so first=3.

What happens in this step

value = nums[0] = 3
first, second, third are all unset

3 becomes first.
Step 1 of 4
4. Solution

Solution

solution.tsTypeScript
function thirdMax(nums) {
  let first = null;
  let second = null;
  let third = null;

  for (const value of nums) {
    if (value === first || value === second || value === third) {
      continue;
    }

    if (first === null || value > first) {
      third = second;
      second = first;
      first = value;
    } else if (second === null || value > second) {
      third = second;
      second = value;
    } else if (third === null || value > third) {
      third = value;
    }
  }

  return third === null ? first : third;
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
nums = [3, 2, 1]1example from the docstring
nums = [1, 2]2fewer than three distinct values, falls back to the maximum
nums = [2, 2, 3, 1]1duplicate values are ignored when tracking distinct maximums
nums = [5]5smallest valid input, only one distinct value
nums = [7, 7, 7]7every element is identical, only one distinct value exists
nums = [-1, -2, -3, -4]-3negative values with a proper third distinct maximum