Largest Unique Number Problem
#1133
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1133.
Given an integer array nums, return the largest integer that only occurs once. If no integer occurs once, return -1.
Example 1:
Input: nums = [5,7,3,9,4,9,8,3,1]
Output: 8
Explanation: The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it is the answer.
Example 2:
Input: nums = [9,9,8,8]
Output: -1
Explanation: There is no number that occurs only once.
Constraints:
1 <= nums.length <= 20000 <= nums[i] <= 1000
Solution
Approach: Count, Then Scan Down
Count how many times each value appears. The values are between 0 and 1000, so an array of 1001 counters does the job; a hash map works for any range.
Then scan the values from 1000 down to 0 and return the first one whose count is exactly 1. It is the largest number that appears once. If the scan finds none, every number is repeated and the answer is -1.
The largest value in the array is not necessarily the answer: in [5,7,3,9,4,9,8,3,1], 9 appears twice, so the answer is 8.
Complexity: O(n + C) time and O(C) extra space, where C = 1001 is the number of possible values.
class Solution:
def largestUniqueNumber(self, nums: List[int]) -> int:
count = [0] * 1001 # values are in [0, 1000]
for x in nums:
count[x] += 1
for x in range(1000, -1, -1): # from the largest value down
if count[x] == 1:
return x
return -1