Largest Unique Number - Problem

Given an integer array nums, return the largest integer that only occurs once. If no integer occurs exactly once, return -1.

An integer occurs once if it appears exactly one time in the array, meaning it has no duplicates.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,2,1]
Output: 3
💡 Note: Numbers 2 and 1 each appear twice, but 3 appears only once. Since 3 is the largest unique number, return 3.
Example 2 — No Unique Numbers
$ Input: nums = [1,1,2,2]
Output: -1
💡 Note: Every number appears exactly twice, so there are no unique numbers. Return -1.
Example 3 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: The array has only one element, which appears exactly once, so return 5.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Largest Unique Number INPUT nums = [2, 1, 3, 2, 1] 2 i=0 1 i=1 3 i=2 2 i=3 1 i=4 Count Occurrences: 1 appears: 2 times 2 appears: 2 times 3 appears: 1 time Only 3 occurs exactly once ALGORITHM STEPS 1 Create Hash Map Store count of each number 2 Count Frequencies Iterate array, increment counts 3 Find Unique Numbers Filter where count == 1 4 Return Maximum Find largest unique or -1 Hash Map: 1: 2 2: 2 3: 1 Green = count is 1 (unique) FINAL RESULT Unique numbers found: 3 Only number with count = 1 Summary - Numbers 1, 2: appear 2x - Number 3: appears 1x - Largest unique = 3 - Answer: 3 [OK] Output: 3 Key Insight: Using a hash map allows O(n) counting of all elements. Then iterate through the map to find elements with count exactly 1. Track the maximum among these unique elements. Time: O(n), Space: O(n) where n is array length. TutorialsPoint - Largest Unique Number | Hash Map Approach
Asked in
Amazon 25 Google 18 Facebook 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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