Katkat

Count and Rank Words in a Paragraph

RobinhoodBackend Engineer · Technical Screen

Last updated

This problem tests string manipulation, hash map usage for frequency counting, and custom sorting logic for deterministic ordering.

Problem Description

Given a large string of text, your task is to count the occurrences of each word and return a list of words ranked by their frequency. A word is defined as a contiguous sequence of alphabetic characters (a-z, A-Z). All words should be treated as case-insensitive (e.g., "Apple" and "apple" are the same).

Requirements

  1. Tokenize the text by splitting on any non-alphabetic characters.
  2. Normalize all words to lowercase.
  3. Return a list of words where the primary sort key is the frequency (descending) and the secondary sort key is the word itself (lexicographically ascending) to ensure deterministic output.

Function Signature

def rank_words(text: str) -> list[str]:
    # Implementation here

Examples

Example 1 Input: "Hello world! Hello." Output: ["hello", "world"] Explanation: "hello" appears twice, "world" appears once.

Example 2 Input: "Alpha, beta, alpha; beta, gamma." Output: ["alpha", "beta", "gamma"] Explanation: "alpha" and "beta" both appear twice, so they are ranked alphabetically after sorting by frequency.

Constraints

  • The input text can contain whitespace, punctuation, and digits, all of which are treated as delimiters.
  • Handle empty strings or strings with no words by returning an empty list.
  • Assume memory capacity allows for the frequency map, but focus on an efficient single-pass tokenization strategy.
  • Time complexity target: O(N log K), where N is the length of the string and K is the number of unique words.

Hints

Hint 1

Use a regular expression or a simple character iteration to identify chunks of consecutive alphabetic characters.

Hint 2

Maintain a dictionary to store word counts as you traverse the string once.

Hint 3

To achieve the deterministic ordering, sort the dictionary items using a tuple key: (-count, word).

Follow-up questions

  • How would your approach change if the input text was too large to fit into memory (e.g., a multi-gigabyte file)?
  • What is the time and space complexity of your solution in terms of the number of words versus the number of unique words?
  • How would you modify your solution to efficiently return only the top K most frequent words?