Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top-K Frequent Item Pairs

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

Your question is Top-K Frequent Item Pairs. 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

Quinstreet comparison surfaces record user sessions as sequences of interacted item IDs. Given these sessions, find the k most frequent unordered item pairs that appeared together in at least one session.

A pair counts at most once per session, even if a user interacted with the same item repeatedly. Return pairs ordered by decreasing frequency. When frequencies tie, order pairs lexicographically by their two item IDs.

Formal Specification

Implement top_k_item_pairs(sessions, k), where sessions is a list of lists of non-negative integer item IDs and k is a positive integer. Return a list of pairs, represented as two-element lists [smaller_id, larger_id]. Return fewer than k pairs if fewer distinct pairs exist.

Constraints

  • 0 <= len(sessions) <= 10^4
  • The total number of interactions is at most 10^5
  • 0 <= item_id <= 10^9
  • 1 <= k <= 10^4
  • Pairs are unordered and contain two distinct item IDs

Function Signature

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