Largest Unique Number - Problem

You're given an array of integers, and your mission is to find the largest number that appears exactly once. Think of it as finding the biggest "loner" in the crowd!

Here's what makes this interesting: a number might appear multiple times in the array, but you only care about those special numbers that appear exactly once. Among all these unique numbers, you want the largest one.

The Challenge:

  • If there are numbers that appear exactly once, return the largest of them
  • If every number appears more than once (no unique numbers), return -1

Example: In [5, 7, 3, 9, 4, 9, 8, 3, 1], the numbers 5, 7, 4, 8, 1 appear exactly once. The largest among these unique numbers is 8.

Input & Output

example_1.py โ€” Python
$ Input: [2, 3, 5, 5]
โ€บ Output: 3
๐Ÿ’ก Note: The unique numbers are 2 and 3. The largest unique number is 3.
example_2.py โ€” Python
$ Input: [5, 7, 3, 9, 4, 9, 8, 3, 1]
โ€บ Output: 8
๐Ÿ’ก Note: Numbers 5, 7, 4, 8, 1 appear exactly once. Among these, 8 is the largest.
example_3.py โ€” Python
$ Input: [9, 9, 8, 8]
โ€บ Output: -1
๐Ÿ’ก Note: All numbers appear more than once, so there are no unique numbers. Return -1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 0 โ‰ค nums[i] โ‰ค 1000
  • Follow up: Can you solve this in O(n) time?

Visualization

Tap to expand
Largest Unique Number SolutionInput Array: [5, 7, 3, 9, 3]57393Frequency Analysis:5: appears 1x7: appears 1x3: appears 2x9: appears 1xโœ“ Uniqueโœ“ Uniqueโœ— Duplicateโœ“ Unique (MAX)Step-by-Step Process:1Process 5: unique, max = 52Process 7: unique, max = 73Process 3: unique, max = 74Process 9: unique, max = 95Process 3 again: now duplicateRESULT: 9Largest unique number
Understanding the Visualization
1
Scan the List
Go through each name and count how many times they appear
2
Track Solo Guests
Keep track of the highest ID among guests who appear exactly once
3
Handle Duplicates
When someone appears multiple times, they're no longer a solo guest
4
Return Result
The highest ID among solo guests is our answer
Key Takeaway
๐ŸŽฏ Key Insight: Use a hash map to count frequencies in O(n) time, while simultaneously tracking the maximum among unique elements. This avoids the need for nested loops and achieves optimal performance.
Asked in
Amazon 25 Google 20 Microsoft 15 Meta 10
28.3K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen