Third Maximum Number

EasyArrays & Hashingtracking extremes

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums, return the third largest **distinct** value in the array. If a third distinct value does not exist, return the largest value instead. The "third distinct largest" means the third largest value when duplicates are collapsed into a single value. For example, in [2, 2, 3, 1] the distinct values are {1, 2, 3}, so the third largest distinct value is 1. Try to solve this in a single pass through the array without sorting.

Examples

Input: nums = [3, 2, 1]
Output: 1
The distinct values are 1, 2, and 3. The third largest distinct value is 1.
Input: nums = [1, 2]
Output: 2
There is no third distinct value, so the largest value (2) is returned.
Input: nums = [2, 2, 3, 1]
Output: 1
The distinct values are 1, 2, and 3. The largest is 3, the second largest is 2, and the third largest is 1.

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.