Search⌘ K

Highest Frequency

Explore how to write a function that finds the most commonly occurring string in an array, returning the earliest one in case of ties. Understand how to track frequencies efficiently with an object and update counts in a single pass, optimizing both time and space complexity for practical coding solutions.

We'll cover the following...

Highest Frequency

Instructions

Write a function that takes an array of strings and returns the most commonly occurring string in that array.

If there are multiple strings with the same high frequency, return the one that finishes its occurrences first, while going left to right through the array.

Input: Array of Strings

Output: String


Node.js
function highestFrequency(strings) {
// Your code here
}

Solution

Node.js
function highestFrequency(strings) {
const frequencies = {};
let maxFrequency = 0;
let mostFrequentString = strings[0];
for(let i = 0; i < strings.length; i++) {
const thisStr = strings[i];
if(frequencies[thisStr] === undefined) {
frequencies[thisStr] = 1;
} else {
frequencies[thisStr]++;
}
if(frequencies[thisStr] > maxFrequency) {
maxFrequency = frequencies[thisStr];
mostFrequentString = thisStr;
}
}
return mostFrequentString;
}

How it Works

Variables

The three variables ...