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
Python Coding With Efficient Structures
00:00
5 left

Python Coding With Efficient Structures

EasyPython

Problem

Apple Music analyzes search terms to identify the most popular queries. Given a list of search terms and an integer k, return the k most frequent terms.

Order the result by decreasing frequency. If two terms have the same frequency, order them lexicographically. Each term should appear only once in the result.

Formal Specification

Implement top_k_search_terms(terms, k):

  • Input: terms, a list of lowercase strings, and k, an integer.
  • Output: a list of exactly k strings ordered by frequency descending, then lexicographically ascending for ties.

Example 1:

Input: terms = ["pop", "rock", "pop", "jazz", "rock", "pop"], k = 2
Output: ["pop", "rock"]

pop appears three times and rock appears twice.

Example 2:

Input: terms = ["beta", "alpha", "beta", "alpha", "gamma"], k = 2
Output: ["alpha", "beta"]

alpha and beta both appear twice, so lexicographic order breaks the tie.

Constraints

  • 1 <= k <= number of distinct terms
  • 1 <= terms.length <= 10^5
  • Each term contains 1 to 30 lowercase English letters
  • The input may contain duplicate terms

Function Signature

def top_k_search_terms(terms, k):
Interviewer

Your question is Python Coding With Efficient Structures. 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.