Select Best Available Venues by Ranking Criteria
Heaps, Sorting & SearchAuto-graded · 15 test casesLast 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 identifieris_open(bool): whether the venue is currently accepting visitorsrating(float): the venue's quality scoredistance(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:
- Venues with a higher
ratingrank above those with a lower rating. - When two venues have the same rating, the one with smaller
distanceranks higher. - If both rating and distance match, the venue with the smaller
idranks 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.
kis at least 1 and at most the number of open venues in the input.- All
ratingvalues lie in the range [0.0, 5.0]. - If fewer than
kvenues 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution proceeds in three stages:
-
Filter out closed venues. Since only open venues can appear in the result, we first build a list containing only those entries where
is_openisTrue. This reduces the problem to ranking a smaller collection. -
Sort by composite key. We need to rank venues by three criteria in sequence. Python's tuple comparison does exactly this: it compares element-by-element from left to right, stopping as soon as one element differs. To encode our rules, we use the key
(-rating, distance, id). The negated rating means higher ratings produce smaller key values and sort earlier. Distance and id remain positive, so smaller values sort first. -
Take the first k elements. After sorting, the top-ranked venues occupy the initial positions. We slice the sorted list to get the first
kentries and extract their IDs. Python's slicing automatically handles the case wherekexceeds the list length by returning all available elements.
Why This Works
The composite key tuple directly encodes the ranking specification. For two venues A and B:
- If A has a higher rating than B, then
-A.rating < -B.rating, so A's key is smaller and A sorts first. - If ratings are equal but A is closer, then
A.distance < B.distance, so A's key is smaller. - If both rating and distance match but A has a smaller ID, then
A.id < B.id, so A's key is smaller.
Because venue IDs are unique, the sort order is deterministic and total—no two venues can have identical keys.
Complexity
Let N be the total number of venues and M the number of open venues (M ≤ N).
- Time: O(N) to filter the input, plus O(M log M) to sort the open venues. In the worst case where all venues are open, this is O(N log N).
- Space: O(M) to store the filtered list. Python's Timsort uses O(M) auxiliary space during sorting. The output list requires O(k) space.
For the constraint limit of 10⁵ venues, this runs efficiently in well under a second.
Alternative: Heap-Based Selection
If k is much smaller than N, we can use a heap to avoid sorting the entire list. The heapq.nsmallest function maintains a bounded heap of size k and runs in O(N log k) time with O(k) space:
import heapq
from typing import List, Dict
def select_top_venues(venues: List[Dict], k: int) -> List[int]:
open_venues = (v for v in venues if v['is_open'])
top_k = heapq.nsmallest(k, open_venues,
key=lambda v: (-v['rating'], v['distance'], v['id']))
return [v['id'] for v in top_k]
This optimization is most useful when k << N, such as selecting the top 10 venues from a million candidates.
Full Solution
from typing import List, Dict
def select_top_venues(venues: List[Dict], k: int) -> List[int]:
# Filter to only venues that are currently open
available = [venue for venue in venues if venue['is_open']]
# Sort by: rating descending, then distance ascending, then id ascending
available.sort(key=lambda v: (-v['rating'], v['distance'], v['id']))
# Extract IDs of the top k venues (slice handles k > length)
return [venue['id'] for venue in available[:k]]