Problem Description: Write a JavaScript program to find count of the most frequent item of an array.
Assume that input is array of integers.
Ex.:
input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
ouptut: 5
Most frequent number in example array is -1. It occures 5 times in input array.
Level: 7kyu
Link to Kata: Find Count of Most Frequent Item in an Array
It was a simple Kata looking at the level of Katas I have solved previously. We were given an array of integers and we have to find the count of the integer which occurred most frequently.
We start by sorting the array in ascending order by using the array prototype Javascript function. Then we create two empty arrays- "ans" and "int_ans". We loop through the sorted array and check if the element on the current index is equal to element at the next index. If it is then we push the element on current index to "int_ans". If it is not then also we push the element on current index to "int_ans" but at the same time we push "int_ans" to "ans" array and re-initialize the "int_ans"
array.
Once we are done looping through the given array we loop though the "ans" array and check for the sub-array with maximum length. Once we find the sub-array with maximum length we output the length as our answer.
Here is a link to the code: Kata Day 18
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment