KatInterview

Order Distinct Letters-Only Tokens by Popularity

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringshash-mapstring-parsingsorting

Last updated

Extract case-insensitive ASCII-letter tokens from text, count them, and list the distinct words by descending count with alphabetical tie-breaks.

Frequency-Ordered Word List

You are given a block of text. Pull out every word it contains, tally how often each distinct word shows up, and return the distinct words arranged from most frequent to least frequent.

What counts as a word

  • A word is a maximal run of consecutive ASCII letters (a-z or A-Z).
  • Every other character acts as a separator. This includes spaces, other whitespace, punctuation, digits, apostrophes, hyphens, and any non-ASCII character.
    • For example, "don't" yields the words don and t, and "abc123def" yields abc and def.
  • Words are compared without regard to case, so Apple, APPLE and apple are all the same word. Report each word in lowercase.

Required output

Return a list of the distinct lowercase words, ordered by:

  1. Number of occurrences, highest first.
  2. For words with the same number of occurrences, ascending alphabetical (lexicographic) order.

Each distinct word appears exactly once in the result. If the text contains no words (including when it is empty), return an empty list.

Function

Implement rank_words_by_count(text), which takes the string text and returns a list of strings.

Constraints

  • text may be empty and may contain letters, digits, whitespace, punctuation, and other characters.
  • Only the ASCII letters a-z and A-Z form words; all else separates them.
  • The result must be fully deterministic, following the ordering rules above.
  • Aim for a single pass over the text to tokenize, then sort only the distinct words (roughly O(N + K log K) for text length N and K distinct words).

Examples

Example 1

Input: rank_words_by_count('Hello world! Hello.')

Output: ['hello', 'world']

Example 2

Input: rank_words_by_count('Alpha, beta, alpha; beta, gamma.')

Output: ['alpha', 'beta', 'gamma']

Hints

Hint 1

Think about two stages: first gather a count for each lowercase word, then order the distinct words.

Hint 2

Be careful to split only on non-ASCII-letter characters; checking `str.isalpha()` would wrongly accept letters like 'e' with an accent.

Hint 3

Sort using a composite key: the negated count (so larger counts come first) paired with the word itself for alphabetical tie-breaks.