Skip to main content
LeetCode 414, Easy. Topics: Array, Sorting. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

Problem

You are given an integer array nums. Return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.

Examples

Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1.
Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third maximum does not exist, so the maximum (2) is returned instead.
Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2’s are counted together since they have the same value). The third distinct maximum is 1.

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
Follow up: Can you find an O(n) solution?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026