338,386 views
2 votes
2 votes
Given an array of integers a, your task is to calculate the digits that occur the most number of times in the array. Return the array of these digits in ascending order.

User Broothy
by
3.4k points

1 Answer

10 votes
10 votes

Answer:

I hope this should be helpful

Step-by-step explanation:

In Javascript

function solution(numbers) {

let hashmap = {};

let ans = [];

for (let i = 0; i < numbers.length; i++) {

// check wether it double or single digit

if (hasOneDigit(numbers[i])) {

// check if it exists in hashmap

// if exist add number of occurence

// check if the occurence is greater than 2

// add if > 2 to the answer list

if (numbers[i] in hashmap) {

hashmap[numbers[i]] = hashmap[numbers[i]] + 1;

if (hashmap[numbers[i]] = 2 && !ans.includes(numbers[i])) {

// max_freq = hashmap[numbers[i]]

ans.push(numbers[i]);

}

// else if (max_freq == hashmap[numbers[i]])

// ans = min(ans, numbers[i])

} else {

hashmap[numbers[i]] = 1;

}

} else {

// change number to string

number = numbers[i].toString();

// loop to iterate every single element

for (let j = 0; j < number.length; j += 1) {

if (+number.charAt(j) in hashmap) {

hashmap[+number.charAt(j)] = hashmap[+number.charAt(j)] + 1;

if (hashmap[+number.charAt(j)] = 2 && !ans.includes(+number.charAt(j))) {

ans.push(+number.charAt(j));

}

} else {

hashmap[+number.charAt(j)] = 1

}

}

}

}

return ans.sort();

}

function hasOneDigit(val) {

return String(Math.abs(val)).charAt(0) == val;

}

console.log(solution([2, 1,42,44, 2, 3,32,7777, 3 , -1]));

User Tola
by
3.3k points