Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Python Coding With Efficient Structures

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

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

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):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output