Find the element that appears once in sorted array - JavaScript

Suppose, we have a sorted array of literals like this ?

const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];

We are required to write a JavaScript function that takes in one such array and returns the first number that appears only once in the array. If there is no such number in the array, we should return false.

For this array, the output should be 6

Approach 1: Linear Scan with State Tracking

This approach uses a boolean flag to track whether we've encountered duplicates of the current element:

const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];

const firstNonDuplicate = arr => {
    let appeared = false;
    for(let i = 0; i < arr.length; i++){
        if(appeared){
            if(arr[i+1] !== arr[i]){
                appeared = false;
            };
        }else{
            if(arr[i+1] === arr[i]){
                appeared = true;
                continue;
            };
            return arr[i];
        };
    };
    return false;
};

console.log(firstNonDuplicate(arr));
6

Approach 2: Simple Linear Search

A more straightforward approach that counts occurrences for each element:

const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];

const findSingleElement = arr => {
    for(let i = 0; i < arr.length; i++){
        // Check if current element is different from neighbors
        let isUnique = true;
        
        // Check left neighbor
        if(i > 0 && arr[i] === arr[i-1]){
            isUnique = false;
        }
        
        // Check right neighbor
        if(i < arr.length - 1 && arr[i] === arr[i+1]){
            isUnique = false;
        }
        
        if(isUnique){
            return arr[i];
        }
    }
    return false;
};

console.log(findSingleElement(arr));
6

How It Works

Both approaches scan the array linearly but use different strategies:

  • Approach 1: Uses state tracking to remember if we're inside a sequence of duplicates
  • Approach 2: Checks each element against its immediate neighbors to determine uniqueness

Comparison

Approach Time Complexity Space Complexity Readability
State Tracking O(n) O(1) Medium
Neighbor Check O(n) O(1) High

Edge Cases

Both functions handle edge cases like empty arrays and arrays with all duplicates by returning false:

console.log(findSingleElement([]));           // false
console.log(findSingleElement([1, 1, 2, 2])); // false
console.log(findSingleElement([1]));          // 1
false
false
1

Conclusion

Both approaches efficiently find the first unique element in O(n) time. The neighbor-checking method is more intuitive and easier to understand for most developers.

Updated on: 2026-03-15T23:18:59+05:30

619 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements