JavaScript Program for the Minimum Index of a Repeating Element in an Array
Last Updated :
03 Nov, 2023
Given an array of integers arr[], The task is to find the index of the first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. In this article, we will find the minimum index of a repeating element in an array in JavaScript.
Examples:
Input: arr[] = {10, 5, 3, 4, 3, 5, 6}
Output: 5
Explanation: 5 is the first element that repeats
Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}
Output: 6
Explanation: 6 is the first element that repeats
Approach 1: Brute force approach
Here we will use nested loops by using for to compare each element with every other element in the array to return duplicates.
Syntax:
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
minIndex = Math.min(minIndex, i);
}
}
}
Example: This example shows the use of the above-explained approach.
Javascript
function findMinIndexBruteForce(arr) {
let minIndex = Infinity;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1;
j < arr.length; j++) {
if (arr[i] === arr[j]) {
minIndex =
Math.min(minIndex, i);
}
}
}
return minIndex !== Infinity
? minIndex : -1;
}
const arr1 = [3, 2, 1, 2, 4, 3];
console.log(findMinIndexBruteForce(arr1));
|
Approach 2: Using an Object (Hash Map)
Here we will use an object to store the elements you have seen so far as keys and their corresponding indices as values. When we encounter a repeating element, check if its index is smaller than the current minimum index.
Syntax:
const seen = {};
Javascript
function findMinIndexWithObject(arr) {
const seen = {};
let minIndex = Infinity;
for (let i = 0; i < arr.length; i++) {
if (seen[arr[i]] !== undefined) {
minIndex = Math
.min(minIndex, seen[arr[i]]);
} else {
seen[arr[i]] = i;
}
}
return minIndex !== Infinity
? minIndex : -1;
}
const arr2 = [3, 2, 1, 2, 4, 3];
console.log(findMinIndexWithObject(arr2));
|
Approach 3: Using a Set
Here we will use a set to keep track of the elements you have seen so far. When we encounter a repeating element, check if it exists in the set. If it does, compare its index with the current minimum index.
Syntax:
const seen = new Set();
Javascript
function findMinIndexWithSet(arr) {
const seen = new Map();
let minIndex = -1;
for (let i = 0; i < arr.length; i++) {
if (seen.has(arr[i])) {
const firstIndex = seen.get(arr[i]);
if (minIndex === -1 || firstIndex < minIndex) {
minIndex = firstIndex;
}
} else {
seen.set(arr[i], i);
}
}
return minIndex;
}
const arr3 = [3, 2, 1, 2, 4, 3];
console.log(findMinIndexWithSet(arr3));
|
Share your thoughts in the comments
Please Login to comment...