Problem 250562 · easy · Phase 02 Linear Data Structures

Third Distinct Maximum

arrays · iteration · best-so-far

Given a non-empty list of integers nums, return the third largest distinct value. If there are fewer than three distinct values, return the largest value instead.

Examples

Input:  nums = [3, 2, 1]
Output: 1

Input:  nums = [1, 2]
Output: 2
Explanation: Only two distinct values, so the maximum is returned.

Input:  nums = [2, 2, 3, 1]
Output: 1
Explanation: The distinct values are 3, 2, 1; the third largest is 1.

Constraints

  • 1 <= len(nums) <= 10**5
  • -10**9 <= nums[i] <= 10**9
  • Target: O(n) time, O(1) extra space (do not sort).

Goals

  • Maintain the top three distinct values in constant space
  • Skip duplicates so equal values do not occupy two slots
  • Fall back to the maximum when fewer than three distinct values exist
Starting Python…