First Element to Occur K Times using JavaScript
Given an array and number, our task is to find the first element that occurs exactly k times in an array using JavaScript.
Example:
Input: array= [1, 2, 3, 4, 2, 5, 6, 4, 2] and k = 3.
Output: 2
Explanation: Here the first element that occurred 3 times in the array is 2
Table of Content
- Using nested for loop
- Using Hash Map
Using nested for loop
In this approach, we iterate over the array, for each element we initialize a count variable to 1. Then using nested for loop we iterate through the array again, starting from the next element. For each subsequent occurrence of the current element we increment the count. If the count become equals k then we will return that element.
Example: The code below shows how we can find the first element that occurs k times using nested for loops.
function firstElement(arr, k) {
for (let i = 0; i < arr.length; i++) {
let count = 1;
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
count++;
}
}
if (count === k) {
return arr[i];
}
}
return -1;
}
const arr = [3, 4, 9, 4, 2, 3, 6, 4];
const k = 3;
console.log(firstElement(arr, k));
Output
4
Using Hash Map
In this approach, we create an empty hash map object to store the count of occurrences of each element. Then we Iterate through the array and for each element we increment its count in the hash map. Then we will Iterate through the array again and for each element we check if its count in the hash map equals k, if it is we will return that element.
Example: The code below shows how we can find the first element that occurs k times using Hash Map.
function first_Element(arr, k) {
let hashMap_obj = {};
for (let i = 0; i < arr.length; i++) {
hashMap_obj[arr[i]] = (hashMap_obj[arr[i]] || 0) + 1;
}
for (let i = 0; i < arr.length; i++) {
if (hashMap_obj[arr[i]] === k) {
return arr[i];
}
}
return -1;
}
const arr = [3, 4,3, 9, 4, 2, 3, 6, 4];
const k = 3;
console.log(first_Element(arr, k));
Output
3