How to usean Object (Hash Map) in Javascript
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 = {};
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));
Output
0
JavaScript Program for the Minimum Index of a Repeating Element in an Array
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
Table of Content
- Brute force approach:
- Using an Object (Hash Map)
- Using a Set:
Contact Us