NeetCode #13LC-1133EasyArrays & HashingNC Algo100
← Back to All Problems

#13 · #1133 · Largest Unique Number(最大唯一数)

📌 Problem Statement & Constraints

Given an integer array nums, return the largest integer that only occurs once. If no integer occurs exactly once, return -1. Constraints: 1 <= nums.length <= 2000, 0 <= nums[i] <= 1000.

💡 Core Algorithmic Approaches

  1. Count the frequency of every value with a hash map.
  2. Scan the frequency map and keep the maximum key whose count is exactly 1.
  3. Initialise the answer to -1 so the no-unique-value case needs no special handling.
  4. An alternative is to sort and check neighbours, but counting is O(n) and simpler.

💻 Benchmark Python3 Implementation

class Solution:
    def largestUniqueNumber(self, nums: List[int]) -> int:
        from collections import Counter
        cnt = Counter(nums)
        res = -1                           # default when nothing is unique
        for v, c in cnt.items():
            if c == 1:
                res = max(res, v)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass to count, one pass over the distinct values (at most n).
💾 Space Complexity
O(k) for the counter, where k is the number of distinct values.

⚠️ Interview Pitfalls & Follow-ups

  • Returning 0 when nothing is unique: the answer must be -1, and 0 is a legitimate unique value in the input range.
  • Sorting and scanning neighbours: O(n log n) and requires care with runs longer than 2.
  • Only tracking the maximum seen value: you must first know the frequency, so a two-phase approach is needed.