Skip to content
dreamcode
dreamcode
← Map
Top Words
Section challenge · AdvancedJavaScript
Reward: +80 XP
PROBLEM

Top Words

Write topWords(text, k) that returns the k most frequent words in text.

  • Words are runs of letters, compared in lowercase (so "Moon" and "moon" are the same word).
  • Sort by count, highest first. Break ties alphabetically.
  • Return fewer than k words if the text does not have that many.

Aim for one pass to count, then one sort.

Examples
topWords("the sky the stars the sky", 2)
→ ["the", "sky"]
topWords("b a c b a b", 3)
→ ["b", "a", "c"]
solution.js
JAVASCRIPT
Saved as you type

Tests

0 of 5 passing
  • •
    counts decide
    topWords("the sky the stars the sky", 2)
    expected ["the", "sky"]
  • •
    three words
    topWords("b a c b a b", 3)
    expected ["b", "a", "c"]
  • •
    empty text
    topWords("", 2)
    expected []
  • •
    case is ignored
    topWords("Moon moon MOON sun", 5)
    expected ["moon", "sun"]
  • •
    ties are alphabetical
    topWords("x y z", 2)
    expected ["x", "y"]
On the line
+80 XP
Pass all 5 tests to claim it.