KatInterview

Budget-Constrained Selection and Graph Distance Query

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchbinary-searchdijkstraprefix-sum

Last 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 weights
  • budgets: 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:

  • n is the number of nodes, m is the number of edges
  • Each of the next m lines contains three tokens: two node identifiers and a positive edge weight
  • The final line contains two node identifiers: the source s and target t

Edges are undirected and all weights are non-negative.

Output:

  • Return a tuple (distance, path) where distance is the shortest distance from s to t, and path is a list of nodes representing one shortest path
  • If t is 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.