call(back)
Algorithms & Data StructureseasySign in to star problemsSign in to track progress

Top N Matches From a Constant-Time Score

A dating app has P users. For a given user u, getMatch(u, v) returns the match score with any other user v in O(1). Describe an algorithm that finds the N best matches for u, where N is much smaller than P, and give its time and space complexity. Then compare it with sorting all scores.

Answered verbally in the Karat screen; the interviewer wants the data structure and the complexities, not code.

Hints

Hint 1

Keep only the best N seen so far in a min-heap; a new score replaces the heap's minimum when it is larger.

Solution

Show the approach

Answer

Scan every other user once, maintaining a min-heap of the N best scores seen so far: push until the heap has N entries, then for each new score compare with the heap's minimum and, if larger, pop and push. Each heap operation is O(log N), so the scan is O(P log N) time and O(N) space. Sorting all scores is O(P log P) time and O(P) space, which is worse on both counts when N << P; quickselect finds the top N in expected O(P) but needs all scores in memory and does not keep them ordered.

Worth saying out loud

  • A min-heap, not a max-heap: the element you need fast access to is the weakest of the current best, because it is the one that gets evicted.
  • If scores stream in over time, the same heap answers "top N so far" at any moment.

Assistant

Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.

Topics

Asked at

Similar Problems6