#414

Third Maximum Number

Easy
ArraySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n log n)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can find the third maximum number in a single pass using a set to track distinct values, which is more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a set to store distinct maximum values.
  2. 2Step 2: Iterate through the array, adding each number to the set.
  3. 3Step 3: If the size of the set exceeds 3, remove the smallest element.
  4. 4Step 4: After processing, if the set has less than 3 elements, return the maximum; otherwise, return the smallest in the set.
solution.py7 lines
1def thirdMax(nums):
2    distinct = set()
3    for num in nums:
4        distinct.add(num)
5        if len(distinct) > 3:
6            distinct.remove(min(distinct))
7    return max(distinct) if len(distinct) < 3 else min(distinct)

Complexity note: This approach runs in O(n) time since we only traverse the list once and use a fixed amount of space for the set.

  • 1Distinct values matter, not duplicates.
  • 2Using a set helps manage unique values efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.