Javascript Codewars Problem: "Highest Rank Number in an Array"
- Get link
- X
- Other Apps
Codewars Problem and solution in Javascript
Objective:
In this challenge, we will solve the “Highest Rank Number in an Array” Codewars Kata using javascript.
Problem statement:
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them.
Examples:
Input : [12, 10, 8, 12, 7, 6, 4, 10, 12]
Output : 12
Input : [12, 10, 8, 12, 7, 6, 4, 10, 12, 10]
Output: 12
Input : [12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10]
Output : 3
Solution Approach:
we will create a hash-map/object from the given array and store the array elements as key of object and number of element's occurrence as value of that key in object.
For understanding hash-map, refer the blog post.
Once done with the object, we will traverse through the object to check which key has highest value and in case of equal values we need to check whose key is higher and accordingly return the result.
Code solution:
function highestRank(arr){
var hash={}
for(let i=0;i<arr.length;i++){
if(hash[arr[i]]) hash[arr[i]]++
else
hash[arr[i]]=1
}
var countMax=0;
var valueMax=0;
for(element in hash){
if(countMax<=hash[element]){
valueMax=Math.max(element,valueMax)
countMax=Math.max(hash[element],countMax)
}
}
return valueMax
}
- Get link
- X
- Other Apps
Comments
C Programming Tutorial for Beginner with Free Certification
ReplyDelete