Largest Unique Number
Problem
You are given an integer array nums. Return the largest integer that appears exactly once in the array. If no integer appears exactly once, return -1.
nums = [5, 7, 3, 9, 4, 9, 8, 3, 1]8def largest_unique_number(nums):
count = {}
for x in nums:
count[x] = count.get(x, 0) + 1
ans = -1
for x, c in count.items():
if c == 1 and x > ans:
ans = x
return ans
function largestUniqueNumber(nums) {
const count = new Map();
for (const x of nums) count.set(x, (count.get(x) || 0) + 1);
let ans = -1;
for (const [x, c] of count) {
if (c === 1 && x > ans) ans = x;
}
return ans;
}
class Solution {
public int largestUniqueNumber(int[] nums) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : nums) count.put(x, count.getOrDefault(x, 0) + 1);
int ans = -1;
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
if (e.getValue() == 1 && e.getKey() > ans) ans = e.getKey();
}
return ans;
}
}
int largestUniqueNumber(vector<int>& nums) {
unordered_map<int, int> count;
for (int x : nums) count[x]++;
int ans = -1;
for (auto& e : count) {
if (e.second == 1 && e.first > ans) ans = e.first;
}
return ans;
}
Explanation
We want the biggest number that appears exactly once. The two things we care about for each value are: how often does it appear, and how big is it. A frequency map handles the first part perfectly.
First pass: walk the array and tally counts into count, so count[x] tells us how many times x shows up.
Second pass: start with ans = -1 (the answer when nothing qualifies). Look at each distinct value x with count c; if c == 1 it is unique, and if it is also bigger than the best we have, we update ans = x.
Example: nums = [5,7,3,9,4,9,8,3,1]. The 9s and 3s repeat, so they are out. The values appearing once are 5, 7, 4, 8, 1, and the largest among them is 8.
If no value has a count of 1, ans never changes and we correctly return -1.