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
Detecting the first non-unique element in array in JavaScript
We are required to write a function that returns the index of the very first element that appears at least twice in the array. If no element appears more than once, we have to return -1. We have to do this in constant space (i.e., without utilizing extra memory).
So, let's write the solution for this problem.
We will use a for loop to iterate over the array and use the Array.prototype.lastIndexOf() method to check for duplicacy.
How It Works
The algorithm works by comparing each element's current index with its last occurrence index using lastIndexOf(). If they don't match, it means the element appears later in the array, making it a duplicate.
Example
The code for this will be ?
const arr1 = [0, 1, 1, 2, 3, 4, 4, 5];
const firstRedundant = arr => {
for(let i = 0; i < arr.length; i++){
if(arr.lastIndexOf(arr[i]) !== i){
return i;
};
};
return -1;
}
console.log(firstRedundant(arr1)); // 1
Output
The output in the console will be ?
1
Step-by-Step Explanation
Let's trace through the array [0, 1, 1, 2, 3, 4, 4, 5]:
const arr = [0, 1, 1, 2, 3, 4, 4, 5];
// i=0: arr[0]=0, lastIndexOf(0)=0 ? match, continue
// i=1: arr[1]=1, lastIndexOf(1)=2 ? no match, return 1
console.log("Element at index 1:", arr[1]);
console.log("Last occurrence of 1 at index:", arr.lastIndexOf(1));
Element at index 1: 1 Last occurrence of 1 at index: 2
Testing with Different Cases
const firstRedundant = arr => {
for(let i = 0; i < arr.length; i++){
if(arr.lastIndexOf(arr[i]) !== i){
return i;
};
};
return -1;
}
// Test cases
console.log(firstRedundant([1, 2, 3, 4])); // -1 (no duplicates)
console.log(firstRedundant([5, 5, 1, 2])); // 0 (first 5 is duplicate)
console.log(firstRedundant([1, 2, 1, 3])); // 0 (first 1 is duplicate)
-1 0 0
Conclusion
This solution efficiently finds the first non-unique element using lastIndexOf() to detect duplicates. The algorithm runs in O(n²) time but uses constant space as required.
