Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the first unique element in a sorted array in 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.
Using Index Comparison Method
Since the array is sorted, we can check if an element is unique by comparing it with its neighbors. An element is unique if it's different from both the previous and next elements.
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
Alternative Approach: Direct Neighbor Comparison
A simpler approach is to directly check if the current element is different from both its previous and next neighbors:
const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];
const findFirstUnique = arr => {
for(let i = 0; i < arr.length; i++){
// Check if element is unique (different from neighbors)
const isUnique = (i === 0 || arr[i] !== arr[i-1]) &&
(i === arr.length-1 || arr[i] !== arr[i+1]);
if(isUnique){
return arr[i];
}
}
return false;
};
console.log(findFirstUnique(arr));
console.log(findFirstUnique([1, 1, 2, 2, 3, 3])); // false - no unique elements
6 false
How It Works
The algorithm works by:
- Iterating through each element in the sorted array
- For each element, checking if it's different from both neighbors
- Returning the first element that meets the uniqueness condition
- Returning false if no unique element is found
Key Points
- Time complexity: O(n) - single pass through the array
- Space complexity: O(1) - constant extra space
- Works only with sorted arrays due to neighbor comparison logic
- Handles edge cases like first and last elements correctly
Conclusion
Finding the first unique element in a sorted array can be efficiently solved using neighbor comparison. The sorted nature of the array allows us to determine uniqueness by checking adjacent elements only.
