Largest Unique Number

array hash-table sorting

Description

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 numbers that occur once are [5,7,4,8,1]. The largest of these is 8.

Example 2:
Input: nums = [9,9,8,8]
Output: -1
Explanation: All numbers appear twice, so there is no unique number.

Example 3:
Input: nums = [5]
Output: 5
Explanation: 5 is the only number and it occurs once, so it is the largest unique number.

Constraints

  • 1 <= nums.length <= 2000
  • 0 <= nums[i] <= 1000

Complexity

Show Complexity
  • Time: O(n)
  • Space: O(n)

Hints

Show Hints
Pattern
Hash map counting
Approach
Use Counter or dict to count frequencies, iterate to find largest with frequency 1
Complexity
Count occurrences, then find max with count = 1

Solutions

Show PY Solution
from collections import defaultdict


def solution(nums: list[int]) -> int:
    m = defaultdict(int)

    for v in nums:
        m[v] += 1

    largest = -1
    for k, v in m.items():
        if v == 1:
            largest = max(largest, k)

    return largest