KatInterview

Select Best Available Venues by Ranking Criteria

Heaps, Sorting & SearchAuto-graded · 15 test cases
HardAuto-gradedHeaps, Sorting & Searchsortingfilteringheap

Last updated

Tests filtering, multi-level sorting with custom tie-breaking rules, and efficient top-K selection from structured data.

You receive a collection of venues, where each venue is represented as a dictionary with these fields:

  • id (int): a unique identifier
  • is_open (bool): whether the venue is currently accepting visitors
  • rating (float): the venue's quality score
  • distance (int): how far the venue is from a reference point

Write a function that identifies the top k venues among those that are open, ranked according to these rules:

  1. Venues with a higher rating rank above those with a lower rating.
  2. When two venues have the same rating, the one with smaller distance ranks higher.
  3. If both rating and distance match, the venue with the smaller id ranks higher.

Return a list containing the IDs of the top k open venues, ordered from best to worst according to the ranking rules above.

Constraints

  • The input list may contain up to 10⁵ venues.
  • k is at least 1 and at most the number of open venues in the input.
  • All rating values lie in the range [0.0, 5.0].
  • If fewer than k venues are open, return all open venues in ranked order.
  • Venue IDs are unique positive integers.

Examples

Example 1

Input: select_top_venues([{'id': 1, 'is_open': True, 'rating': 4.5, 'distance': 10}, {'id': 2, 'is_open': False, 'rating': 5, 'distance': 2}, {'id': 3, 'is_open': True, 'rating': 4.5, 'distance': 5}], 2)

Output: [3, 1]

Example 2

Input: select_top_venues([{'id': 10, 'is_open': True, 'rating': 5, 'distance': 20}, {'id': 4, 'is_open': True, 'rating': 4.9, 'distance': 1}, {'id': 7, 'is_open': True, 'rating': 5, 'distance': 10}], 2)

Output: [7, 10]

Hints

Hint 1

Start by removing all venues where is_open is False—they cannot appear in the result.

Hint 2

Use a tuple as your sort key to encode all three ranking rules in one comparison. Think about how to reverse the rating comparison while keeping distance and id ascending.

Hint 3

Python's list slicing gracefully handles cases where k exceeds the list length, returning all available elements.