Skip to content
CodeKruPro

Sort words by how often they occur

Coding problemEasy-MediumAsked in: Accenture, Wipro

Given a sentence of lower-case words, count how many times each word occurs. Return one entry per distinct word, written as the word, an equals sign and the count (such as "the=3").

Order the entries by count, highest first. When two words have the same count, put them in alphabetical order. Words are separated by one or more spaces, and the sentence may start or end with spaces.

Examples

Example 1
Input: sentence = "the cat the hat the cat"
Output: ["the=3","cat=2","hat=1"]
Example 2
Input: sentence = "b a b a"
Output: ["a=2","b=2"]
Same count, so alphabetical order decides.
Example 3
Input: sentence = ""
Output: []

Constraints

  • The length of sentence is between 0 and 100,000
  • Words hold lower-case English letters; only the space character separates them

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in