Budget-Constrained Selection and Graph Distance Query
Heaps, Sorting & SearchModel answerLast updated
Find how many sorted items fit within a budget using prefix sums and binary search, then parse a graph and compute the shortest path between two nodes.
You have two independent tasks to solve:
Task 1: Item Selection Within Budget
You are given a list of item weights in ascending order and one or more budget values. For each budget, determine the maximum number of items you can select such that their total weight does not exceed the budget.
Input:
weights: A sorted list of non-negative integers representing item weightsbudgets: A list of non-negative integers representing capacity constraints
Output:
- For each budget, return the maximum count of items whose combined weight stays within that budget
Example:
weights = [1, 2, 3, 5, 8]
budgets = [0, 4, 6, 11, 100]
output = [0, 2, 3, 4, 5]
Task 2: Shortest Path in a Weighted Graph
You receive graph data as a string in the following format:
n m
u1 v1 w1
u2 v2 w2
...
um vm wm
s t
Where:
nis the number of nodes,mis the number of edges- Each of the next
mlines contains three tokens: two node identifiers and a positive edge weight - The final line contains two node identifiers: the source
sand targett
Edges are undirected and all weights are non-negative.
Output:
- Return a tuple
(distance, path)wheredistanceis the shortest distance fromstot, andpathis a list of nodes representing one shortest path - If
tis unreachable, return(-1, [])
Example:
Input:
4 5
A B 1
B C 2
A C 5
C D 1
B D 7
A D
Output: (4, ['A', 'B', 'C', 'D'])
Write code to solve both tasks efficiently.
Hints
Hint 1
For Task 1, since all items have equal value, which items should you prioritize to maximize count?
Hint 2
Task 1 can be solved by precomputing cumulative sums and using binary search to find the threshold.
Hint 3
For Task 2, Dijkstra's algorithm works when all edge weights are non-negative; use a min-heap and track parent pointers to reconstruct the path.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Overview
These two problems test different algorithmic patterns: greedy optimization with binary search for the first, and shortest-path computation for the second.
Task 1: Item Selection Within Budget
Approach
When all items have identical value, the optimal strategy is always to select the lightest items available. Since the weight list is already sorted, the best set of k items is simply the first k items.
Key insight: If we want to maximize count within budget B, we should greedily pick items from lightest to heaviest until adding the next item would exceed B.
Rather than iterate through items for each budget query, we can:
- Precompute a prefix sum array where
prefix[k]represents the total weight of the firstkitems - For each budget
B, binary search for the largestkwhereprefix[k] ≤ B
Why this works:
- The prefix sum array is monotonically non-decreasing (all weights are non-negative)
- This creates a perfect scenario for binary search: find the rightmost position where a condition holds
- Using
bisect_right(prefix, B) - 1gives us the answer directly
Complexity
- Preprocessing: O(n) to build the prefix array
- Per query: O(log n) for binary search
- Space: O(n) for the prefix array
This is vastly more efficient than dynamic programming, which would be O(n·W) per query where W is the budget value.
Edge Cases
- Empty weight list → answer is always 0
- Budget of 0 → can still select zero-weight items if they exist
- Very large budgets → answer capped at the total number of items
- All items heavier than budget → answer is 0
Task 2: Shortest Path in Weighted Graph
Approach
This requires parsing custom input and then applying Dijkstra's algorithm for shortest path computation.
Step 1: Parse the Input
- Tokenize the entire string
- Extract
nandmfrom the first two tokens - Build an adjacency list representation:
graph[node] = [(neighbor, weight), ...] - Handle nodes as strings to support both numeric and alphabetic labels
- Since edges are undirected, add each edge in both directions
- Extract source
sand targettfrom the final tokens
Step 2: Dijkstra's Algorithm Dijkstra finds the shortest path when all edge weights are non-negative:
- Maintain a min-heap of
(distance, node)pairs - Track the best-known distance to each node
- Track parent pointers to reconstruct the path
- Use lazy deletion: when popping an entry from the heap, skip it if we've already found a better path to that node
- Terminate early when we pop the target node (its distance is finalized)
Why Dijkstra is correct here:
When we extract a node from the heap with distance d, we know no future path can improve that distance. Any alternate path must go through nodes we haven't processed yet, which have tentative distances ≥ d, and adding non-negative edges can only increase the distance further.
Path reconstruction:
Walk backward from t using the parent map, then reverse to get the forward path.
Complexity
- Parsing: O(V + E) to build the adjacency list
- Dijkstra: O((V + E) log V) with a binary heap
- Space: O(V + E) for the graph structure and auxiliary data
Edge Cases
- Source equals target → distance is 0, path is
[s] - Target unreachable → return
(-1, []) - Multiple edges between the same nodes → Dijkstra naturally picks the minimum weight
- Isolated nodes → handled correctly by the adjacency list structure
- Self-loops → harmless, won't affect shortest paths
Important Limitation
If any edge has negative weight, Dijkstra produces incorrect results. In that case, you'd need Bellman-Ford algorithm (O(VE) time) which can also detect negative cycles.
Implementation
import heapq
from bisect import bisect_right
from collections import defaultdict
from itertools import accumulate
def max_items_within_budget(weights, budgets):
"""
Returns the maximum count of items for each budget.
weights: sorted list of non-negative integers
budgets: list of non-negative integers
"""
if not weights:
return [0] * len(budgets)
# Build prefix sum: prefix[k] = sum of first k items
prefix = [0] + list(accumulate(weights))
# For each budget, binary search for the threshold
results = []
for budget in budgets:
# Find largest k where prefix[k] <= budget
max_count = bisect_right(prefix, budget) - 1
results.append(max(0, max_count))
return results
def parse_graph_input(text):
"""Parse the custom graph format into an adjacency list."""
tokens = text.split()
n, m = int(tokens[0]), int(tokens[1])
graph = defaultdict(list)
idx = 2
# Read m edges
for _ in range(m):
u, v, w = tokens[idx], tokens[idx + 1], int(tokens[idx + 2])
idx += 3
# Undirected: add edge in both directions
graph[u].append((v, w))
graph[v].append((u, w))
# Read source and target
s, t = tokens[idx], tokens[idx + 1]
return graph, s, t
def dijkstra_shortest_path(graph, source, target):
"""
Compute shortest path using Dijkstra's algorithm.
Returns (distance, path) or (-1, []) if unreachable.
"""
if source == target:
return 0, [source]
# Track best distances and parent pointers
dist = {source: 0}
parent = {source: None}
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
# Lazy deletion: skip stale entries
if d > dist.get(u, float('inf')):
continue
# Early exit: target reached
if u == target:
# Reconstruct path
path = []
current = target
while current is not None:
path.append(current)
current = parent[current]
return d, path[::-1]
# Relax edges
for neighbor, weight in graph.get(u, []):
new_dist = d + weight
if new_dist < dist.get(neighbor, float('inf')):
dist[neighbor] = new_dist
parent[neighbor] = u
heapq.heappush(heap, (new_dist, neighbor))
# Target not reachable
return -1, []
def solve_graph_query(text):
"""Complete solution for Task 2."""
graph, source, target = parse_graph_input(text)
return dijkstra_shortest_path(graph, source, target)
# Example usage
if __name__ == "__main__":
# Task 1
weights = [1, 2, 3, 5, 8]
budgets = [0, 4, 6, 11, 100]
print(max_items_within_budget(weights, budgets))
# Output: [0, 2, 3, 4, 5]
# Task 2
graph_input = """4 5
A B 1
B C 2
A C 5
C D 1
B D 7
A D"""
print(solve_graph_query(graph_input))
# Output: (4, ['A', 'B', 'C', 'D'])
Common Mistakes
Task 1:
- Using dynamic programming unnecessarily (pseudo-polynomial time, much slower)
- Forgetting that sorted order enables a greedy approach
- Not handling edge cases like empty lists or zero budgets
Task 2:
- Assuming nodes are integers 0 through n-1 (they can be any string labels)
- Forgetting to track parent pointers for path reconstruction
- Not implementing lazy deletion in Dijkstra (leads to redundant processing)
- Continuing after finding the target instead of stopping early
- Assuming edges are directed when they're specified as undirected
Both:
- Not clarifying assumptions before coding
- Poor handling of boundary conditions