ATM Machine Withdraw Request
April 13, 2025
1 min
Implement a method that will list out the words that have a maximum number of occurrence in a paragraph.
Assumption: Delimiter between two next words is a space.
An example of input/output
- Input: “I want to know how to achieve the things I want”
- Output: [to, I, want]
To implement a method that lists out the words with the maximum number of occurrences in a paragraph, we can follow these steps:
function findMostFrequentWords(paragraph) {const words = paragraph.split(' ').map(word => word.toLowerCase()); // Split by space and convert to lowercaseconst wordCount = {};// Count the occurrences of each wordfor (const word of words) {wordCount[word] = (wordCount[word] || 0) + 1;}// Find the maximum occurrence countlet maxCount = 0;for (const count of Object.values(wordCount)) {maxCount = Math.max(maxCount, count);}// Collect all words that have the maximum countconst result = [];for (const [word, count] of Object.entries(wordCount)) {if (count === maxCount) {result.push(word);}}return result;}// ✅ Example usage:const input = "I want to know how to achieve the things I want";console.log(findMostFrequentWords(input)); // Output: ['to', 'I', 'want']
split(' ')
: Splits the input paragraph into an array of words by spaces.map(word => word.toLowerCase())
: Converts each word to lowercase to make the comparison case-insensitive.wordCount
: This object stores the frequency of each word.maxCount
: Tracks the maximum frequency of any word.For the input:
"I want to know how to achieve the things I want"
Words and their frequencies:
I
: 2want
: 2to
: 2know
: 1how
: 1achieve
: 1the
: 1things
: 1The words with the highest frequency (2 occurrences) are: ["to", "I", "want"]
.
n
is the number of words in the paragraph. Let me know if you’d like further optimizations or need this code in another language!
Quick Links
Legal Stuff
Social Media