Smallest Venue Set That Fits a Group
Dynamic ProgrammingAuto-graded · 20 test casesLast updated
Tests capacity-constrained subset selection with multi-level tie-breaking: fewest venues, then minimum total capacity, then lexicographically smallest ID list.
Problem
You are managing a booking platform. Each venue is described by a dictionary with three keys:
"id"— an integer identifier"neighborhood"— a string indicating which part of the city the venue is located in"capacity"— a positive integer for the number of guests the venue can accommodate
Given a target_neighborhood (string) and a group_size (int), find the smallest possible set of venues drawn exclusively from target_neighborhood whose combined capacity is at least group_size.
Selection rules
- Feasibility — the combined
capacityof the chosen venues must be ≥group_size. - Minimize count — among all feasible sets, choose one with the fewest venues.
- Minimize total — if several sets tie on count, prefer the one whose combined capacity is smallest (i.e., waste as few slots as possible).
- Lexicographic fallback — if sets still tie on both count and total, choose the one whose sorted list of IDs is lexicographically smallest.
Return the chosen IDs as an ascending list of integers. Return an empty list if no feasible set exists or if group_size ≤ 0.
Constraints
1 ≤ len(venues) ≤ 201 ≤ capacity ≤ 1000for each venue- IDs are positive integers; assume they are unique within the input
group_sizemay be any integer (including non-positive values)- Venues outside
target_neighborhoodmust be ignored entirely - Neighborhood strings are case-sensitive
Examples
Example 1
Input: smallest_venue_set([{'id': 1, 'neighborhood': 'downtown', 'capacity': 5}, {'id': 2, 'neighborhood': 'downtown', 'capacity': 3}, {'id': 3, 'neighborhood': 'downtown', 'capacity': 1}, {'id': 4, 'neighborhood': 'uptown', 'capacity': 4}, {'id': 5, 'neighborhood': 'uptown', 'capacity': 2}], 'downtown', 6)
Output: [1, 3]
Example 2
Input: smallest_venue_set([{'id': 1, 'neighborhood': 'downtown', 'capacity': 5}, {'id': 2, 'neighborhood': 'downtown', 'capacity': 3}, {'id': 3, 'neighborhood': 'downtown', 'capacity': 1}, {'id': 4, 'neighborhood': 'uptown', 'capacity': 4}, {'id': 5, 'neighborhood': 'uptown', 'capacity': 2}], 'downtown', 3)
Output: [2]
Example 3
Input: smallest_venue_set([{'id': 1, 'neighborhood': 'downtown', 'capacity': 5}, {'id': 2, 'neighborhood': 'downtown', 'capacity': 3}, {'id': 3, 'neighborhood': 'downtown', 'capacity': 1}, {'id': 4, 'neighborhood': 'uptown', 'capacity': 4}, {'id': 5, 'neighborhood': 'uptown', 'capacity': 2}], 'downtown', 16)
Output: []
Example 4
Input: smallest_venue_set([{'id': 1, 'neighborhood': 'downtown', 'capacity': 5}, {'id': 2, 'neighborhood': 'downtown', 'capacity': 3}, {'id': 3, 'neighborhood': 'downtown', 'capacity': 1}], 'downtown', 10)
Output: []
Hints
Hint 1
Start by filtering out every venue not in target_neighborhood — they can never appear in the answer. Then think about what the minimum feasible count must be: if you sort filtered capacities descending and greedily accumulate, you get the smallest possible k quickly. Does that greedy approach also nail down which specific venues to pick?
Hint 2
Greedy gives you k but not the right subset — there can be many size-k subsets that all reach group_size. To pick the one with the smallest total, you need to explore all reachable sums exactly. A 0/1 knapsack-style DP over exact sums works: keep, for every reachable total, the best subset (fewest items, then lex-smallest IDs) that achieves it.
Hint 3
Once the DP is built, scan every entry whose total ≥ group_size and pick the winner by comparing (count, total, sorted_id_tuple). Be careful to iterate over a snapshot of the DP table when processing each venue — updating in place would let a single venue be used more than once.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Filter
Only venues in target_neighborhood are eligible. Venues from other neighborhoods are ignored completely before any further processing.
Step 2 — Why greedy is not enough
The minimum count k is easy to find: sort eligible capacities descending and take the top k that first reaches group_size. But greedy does not tell you which size-k subset has the smallest total — there may be many. That second criterion is essentially a subset-sum problem, which is NP-hard in general, so an exact search is required.
Step 3 — 0/1 knapsack DP over exact sums
Maintain a dictionary best that maps every reachable capacity-total to the "best" subset achieving it, stored as a sorted tuple of IDs. "Best" means smallest (count, id_tuple) under lexicographic comparison.
Initialization: best = {0: ()} (zero venues chosen, zero total capacity).
For each eligible venue (id, capacity):
- Take a snapshot of the current
best(this is the "skip this venue" branch). - For every
(total, ids)in the snapshot, formnew_total = total + capacityandnew_ids = sorted(ids + (id,)). - Accept
new_idsintoupdated[new_total]only if it beats whatever is already there under(count, id_tuple)comparison. - Replace
bestwithupdated.
Processing a snapshot — not the live table — guarantees each venue appears at most once per subset.
Step 4 — Extract the answer
Collect every entry with total >= group_size. The global winner is the minimum of these entries under the key (count, total, ids), which enforces all three tie-breaking levels simultaneously. Return its ID list in ascending order; if no entry qualifies, return [].
Why it is correct
Optimal substructure. For a fixed sum s, the best subset either excludes the current venue (inheriting the best predecessor for s) or includes it (taking the best predecessor for s - capacity and appending the current ID). Comparing both options with the same (count, id_tuple) key always selects the true optimum, because inserting the same ID into two equal-length tuples preserves their relative lexicographic order.
Determinism. All tie-breaking is resolved by explicit tuple comparisons, so the result is independent of dictionary iteration order or input order.
Edge cases
group_size <= 0: returns[]by contract — the empty set is technically feasible but excluded.- No eligible venues, or their combined capacity falls short:
bestnever gains a feasible entry, so the result is[]. - Duplicate capacity values: produce the same DP totals; the lex-smaller ID tuple wins, keeping the output deterministic.
- Zero-capacity venues: never help (they increase count without increasing total), so the DP will never prefer including them in a feasible subset.
Complexity
Let n be the number of eligible venues and C their combined capacity total.
- Time: O(n · S · n log n) where
S ≤ min(2ⁿ, C + 1)is the number of distinct reachable sums. Sorting a tuple of up tonIDs costsO(n log n). In practice this is pseudo-polynomial: roughly O(n² · C) up to the log factor. - Space: O(S · n) — each of the
Sentries stores a tuple of up tonIDs.
If C is very large, the dictionary only holds reachable sums (not all integers up to C), so sparse inputs stay manageable. For truly massive inputs, note that the exact tie-break on total is subset-sum hard; there is no known polynomial-time exact algorithm unless P = NP.
Full solution
from typing import Dict, List
def smallest_venue_set(venues: List[Dict], target_neighborhood: str, group_size: int) -> List[int]:
if group_size <= 0:
return []
best = {0: ()}
for venue in venues:
if venue["neighborhood"] != target_neighborhood:
continue
capacity = venue["capacity"]
vid = venue["id"]
updated = dict(best)
for total, ids in best.items():
new_total = total + capacity
new_ids = tuple(sorted(ids + (vid,)))
existing = updated.get(new_total)
if existing is None or (len(new_ids), new_ids) < (len(existing), existing):
updated[new_total] = new_ids
best = updated
feasible = [
(len(ids), total, ids)
for total, ids in best.items()
if total >= group_size
]
if not feasible:
return []
return list(min(feasible)[2])