Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Top Phrases Extraction Function
00:00
5 left

Top Phrases Extraction Function

HardPython

Problem

Textio analyzes language patterns in writing. Given a text string and an integer k, return the k most frequent repeated phrases, where each phrase contains at least two words.

A phrase is a contiguous sequence of words within one sentence. Matching is case-insensitive, and punctuation separates sentences when it is ., !, or ?. Ignore other punctuation when identifying words. A shorter phrase is redundant when it appears inside a longer phrase with the same frequency. Do not return redundant phrases. This preserves the longest repeated wording rather than separately reporting all of its subphrases.

Return objects containing phrase and count. Sort results by decreasing frequency, then decreasing word count, then lexicographic phrase order. Return fewer than k results when fewer qualifying phrases exist.

Formal Specification

Implement top_phrases(text, k), where text is a string and k is a positive integer. Return a list of dictionaries in the form {"phrase": string, "count": integer}. Only phrases occurring at least twice qualify.

Constraints

  • 1 <= len(text) <= 100000
  • 1 <= k <= 1000
  • Words contain letters or digits, with an optional internal apostrophe
  • A sentence contains at most 500 words
  • Matching is case-insensitive

Function Signature

def top_phrases(text, k):
Interviewer

Your question is Top Phrases Extraction Function. Start with the requirements in the Question tab.

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.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.