Largest Unique Number — Easy Problem & Solution

Given an array nums, return the largest value that appears exactly once. If every value repeats, return -1.

  • Difficulty: Easy
  • Topics: Arrays, Hash Table, Sorting
  • Asked at: Amazon, TCS, Zoho
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Given an array nums, return the largest value that appears exactly once.

If every value repeats, return -1.

Example 1

Input: nums = [5,7,3,9,4,9,8,3,1]
Output: 8
Explanation: 9 and 3 repeat; among the rest 8 is the largest.

Example 2

Input: nums = [9,9,8,8]
Output: -1
Explanation: Nothing appears exactly once.

Example 3

Input: nums = [0]
Output: 0

Constraints

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

How to solve Largest Unique Number

Uniqueness is a global property, so it needs a full tally before any decision. A second pass over the tallies then picks the largest key with a count of one.

Approach

  1. Count occurrences of every value.
  2. Walk the counts and consider only the values whose count is exactly 1.
  3. Return the largest such value, or -1 if there is none.

Why it works

A single pass cannot decide uniqueness, because a later duplicate would invalidate an earlier decision — which is why the two-pass structure is essential here.

Complexity

  • Time — O(n + V)
  • Space — O(V)

Pitfalls

  • Returning the first unique value found rather than the largest.
  • 0 is a legitimate answer, so -1 must be the sentinel, not 0.

Reference solution

Python

from typing import List

def largestUniqueNumber(nums: List[int]) -> int:
    count = {}
    for x in nums:
        count[x] = count.get(x, 0) + 1
    best = -1
    for v, c in count.items():
        if c == 1 and v > best:
            best = v
    return best

JavaScript

var largestUniqueNumber = function(nums) {
    var count = {};
    for (var i = 0; i < nums.length; i++) {
        var k = String(nums[i]);
        count[k] = (count[k] === undefined ? 0 : count[k]) + 1;
    }
    var best = -1;
    var keys = Object.keys(count);
    for (var j = 0; j < keys.length; j++) {
        if (count[keys[j]] === 1) {
            var v = Number(keys[j]);
            if (v > best) best = v;
        }
    }
    return best;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue