Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top N Word Counting

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

Your question is Top N Word Counting. 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

Medium's article tools need to identify the most frequently used words in a paragraph. Given a paragraph and an integer n, return the top n words ranked by descending frequency. Break ties alphabetically.

Words are contiguous sequences of English letters. Matching is case-insensitive, and punctuation is ignored. Return each result as a two-element list containing the lowercase word and its frequency. If n exceeds the number of distinct words, return every distinct word.

Formal Specification

  • Input: paragraph, a non-empty string, and n, a positive integer.
  • Output: A list of [word, frequency] pairs ordered by decreasing frequency, then alphabetically for equal frequencies.

Constraints

  • 1 <= len(paragraph) <= 10^5
  • 1 <= n <= 10^4
  • Words contain only English letters.
  • The paragraph contains at least one word.
  • There may be up to 10^4 distinct words.

Function Signature

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