Finding the largest non-repeating number in an array in JavaScript

In JavaScript, finding the largest non-repeating number in an array requires tracking element frequencies and identifying unique values. This problem becomes efficient when we know the value range constraints.

We need to write a function that takes an array of integers and returns the largest number that appears exactly once. If no unique number exists, return -1.

The constraint given is that all array elements satisfy:

0 < arr[i] < 101

This means all values are between 1 and 100, inclusive.

Example Input and Output

For the input array:

const arr = [35, 37, 33, 39, 34, 39, 38, 31];

The expected output is:

38

Because 38 is the largest number that appears only once in the array.

Frequency Array Approach

Since values are bounded (1-100), we can use a frequency array to count occurrences efficiently. Then traverse from the highest possible value downward to find the largest unique number.

const arr = [35, 37, 33, 39, 34, 39, 38, 31];

const pickGreatestUnique = (arr = [], bound = 100) => {
    const frequency = Array(bound).fill(0);
    
    // Count frequency of each number
    for(let i = 0; i < arr.length; i++){
        const num = arr[i];
        frequency[num - 1]++;  // num-1 because array is 0-indexed
    }
    
    // Traverse from highest to lowest to find largest unique
    for(let j = bound - 1; j >= 0; j--){
        if(frequency[j] === 1){
            return j + 1;  // j+1 because we stored num-1
        }
    }
    
    return -1;  // No unique number found
}

console.log(pickGreatestUnique(arr));
38

How It Works

The algorithm works in two phases:

  1. Frequency Counting: Create an array of size 100 and count occurrences of each number
  2. Reverse Traversal: Start from index 99 (value 100) and work backward to find the first frequency of 1

Alternative Example

const testCases = [
    [1, 2, 3, 2, 1],        // Expected: 3
    [5, 5, 4, 4, 3, 3],     // Expected: -1 (no unique)
    [10, 20, 10, 30, 20]    // Expected: 30
];

testCases.forEach((arr, index) => {
    console.log(`Test ${index + 1}: [${arr}] -> ${pickGreatestUnique(arr)}`);
});
Test 1: [1,2,3,2,1] -> 3
Test 2: [5,5,4,4,3,3] -> -1
Test 3: [10,20,10,30,20] -> 30

Time and Space Complexity

Aspect Complexity Explanation
Time O(n + k) n for counting + k for traversal (k=100)
Space O(k) Fixed array of size 100

Conclusion

The frequency array approach efficiently solves this problem in O(n) time by leveraging the bounded input constraint. This method is optimal for scenarios with known value ranges.

Updated on: 2026-03-15T23:19:00+05:30

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements