FastPrepTop Ten Most Frequent Words in a Book
Problem · Hash Table

Top Ten Most Frequent Words in a Book

Learn this problem
MediumRobinhood logoRobinhoodFULLTIMEPHONE SCREEN

Problem statement

You are given a string text containing a book. Split it into maximal ASCII-letter-or-digit words. Matching is case-insensitive, so normalize every word to lowercase.

Return at most ten entries in the form "word frequency", ordered by descending frequency. Break equal-frequency ties lexicographically by normalized word. If the book contains fewer than ten distinct words, return every distinct word.

Function

topTenWords(text: String) → String[]

Examples

Example 1

text = "Red blue red GREEN blue red"return = ["red 3","blue 2","green 1"]

Case variants are merged. Only three distinct normalized words occur.

Example 2

text = "k j i h g f e d c b a"return = ["a 1","b 1","c 1","d 1","e 1","f 1","g 1","h 1","i 1","j 1"]

All eleven words tie, so lexical order selects the first ten and excludes k.

Constraints

  • 1 <= text.length <= 1000000
  • text contains printable ASCII characters and whitespace.

More Robinhood problems

drafts saved locally
public String[] topTenWords(String text) {
  // Write your code here.
}
text"Red blue red GREEN blue red"
expected["red 3", "blue 2", "green 1"]
checking account