Return the Third Distinct Maximum or the Maximum

Quick Overview

Practice returning the third-largest distinct integer with the correct maximum fallback. Handle duplicate values, negative inputs, and both signed 32-bit endpoints.

Return the Third Distinct Maximum or the Maximum

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

# Return the Third Distinct Maximum or the Maximum Given an integer array `nums`, return its third-largest distinct value. If the array has fewer than three distinct values, return its largest value instead. ### Function `int thirdMax(vector<int>& nums)` ### Example 1 ```text Input: nums = [9,5,5,2] Output: 2 ``` The distinct values in decreasing order are `9,5,2`. Repeating `5` does not give it another rank. ### Example 2 ```text Input: nums = [-2147483648,-2147483648,7] Output: 7 ``` Only two distinct values exist, so return the maximum. ### Constraints - `1 <= nums.length <= 10000`. - `-2147483648 <= nums[i] <= 2147483647`. ### Clarifications Ranks are assigned to distinct values, not occurrences. Negative numbers and the minimum signed 32-bit value are valid inputs. Return a value, not its array index. ### What a Strong Answer Covers - Repeated values and fewer than three distinct values. - The full signed 32-bit input domain. - Why the returned value has the required distinct rank. - Correctness and resource bounds. ### Follow-up Questions Can you solve this in `O(n)` time?

Overview: Practice returning the third-largest distinct integer with the correct maximum fallback. Handle duplicate values, negative inputs, and both signed 32-bit endpoints.

Google logo
Google
easySoftware EngineerOtherCoding & Algorithms
0
0

Return the Third Distinct Maximum or the Maximum

Given an integer array nums, return its third-largest distinct value. If the array has fewer than three distinct values, return its largest value instead.

Function

int thirdMax(vector<int>& nums)

Example 1

Input: nums = [9,5,5,2]
Output: 2

The distinct values in decreasing order are 9,5,2. Repeating 5 does not give it another rank.

Example 2

Input: nums = [-2147483648,-2147483648,7]
Output: 7

Only two distinct values exist, so return the maximum.

Constraints

  • 1 <= nums.length <= 10000 .
  • -2147483648 <= nums[i] <= 2147483647 .

Clarifications

Ranks are assigned to distinct values, not occurrences. Negative numbers and the minimum signed 32-bit value are valid inputs. Return a value, not its array index.

What a Strong Answer Covers Guidance

  • Repeated values and fewer than three distinct values.
  • The full signed 32-bit input domain.
  • Why the returned value has the required distinct rank.
  • Correctness and resource bounds.

Follow-up Questions Guidance

Can you solve this in O(n) time?