How to usean Array to Store Indices in Javascript
In this approach, we utilize an array to store the indices of elements as we traverse the input array. When we encounter a repeating element, we can directly access its index from the array and compare it with the current minimum index.
- Create an array
indices
to store the indices of elements. - Initialize the
minIndex
variable to Infinity. - Iterate through the input array:
- If the current element already exists in the
indices
array, updateminIndex
with the smaller value between the current minimum index and the index of the repeating element. - Otherwise, push the index of the current element into the
indices
array.
- If the current element already exists in the
- After iterating through the entire array, check if
minIndex
has been updated. If it has, returnminIndex
; otherwise, return -1, indicating that there are no repeating elements.
Example:
function findMinIndexWithArray(arr) {
const indices = []; // Array to store indices of elements
let minIndex = Infinity;
for (let i = 0; i < arr.length; i++) {
const element = arr[i];
if (indices[element] !== undefined) {
minIndex = Math.min(minIndex, indices[element]);
} else {
indices[element] = i;
}
}
return minIndex !== Infinity ? minIndex : -1;
}
const arr = [3, 2, 1, 2, 4, 3];
console.log(findMinIndexWithArray(arr)); // Output: 0
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