Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Find Top N Word Frequencies

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Find Top N Word Frequencies. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Warner Music Group can analyze words appearing in music catalog metadata and editorial text. Given a string and an integer n, return the n most frequently occurring words.

Formal Specification

Implement top_words(text, n). Treat words as contiguous sequences of English letters A-Z, ignoring case and all other characters. Return a list of lowercase words ordered by decreasing frequency. If two words have the same frequency, order them alphabetically. Return fewer than n words when the text contains fewer distinct words. If n is zero or the text contains no words, return an empty list.

Constraints

  • 0 <= len(text) <= 10^5
  • 0 <= n <= 10^4
  • Words are contiguous sequences of English letters A-Z.
  • Matching is case-insensitive.
  • Punctuation and non-letter characters are separators.
  • The output contains no duplicate words.

Function Signature

def top_words(text, n):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output