FastPrep0/1 Knapsack with Weight and Volume Limits
Problems/0/1 Knapsack with Weight and Volume Limits

0/1 Knapsack with Weight and Volume Limits

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW
QuestionExamples

Problem statement

Source note: In an in-person Google onsite round, the candidate got a dynamic programming question that they only describe as being like a knapsack with two dimensions. They wrote a cubic-time solution and tried to get it down to quadratic time.

The report gives no statement, inputs, or limits, and does not say what the two dimensions were, so the real question may have been a knapsack in disguise. This practice version picks weight and volume as the two limits: each item has a weight, a volume, and a value, each item can be used once, and both totals must stay within their limits. It asks only for the best total value.

The judged task matches the report at about 30%.

You are given a list of items. Each item is items[i] = [weight, volume, value]. You also get two limits, maxWeight and maxVolume.

Pick any group of items. Each item can be picked at most once. The total weight of the picked items must be at most maxWeight, and their total volume must be at most maxVolume.

The problem statement continues
Pro

Examples

Example 1

items = [[1,2,6],[2,1,5],[2,2,9],[3,3,10]]maxWeight = 4maxVolume = 4return = 15

Pick items[0] and items[2]. Their weight is 1 + 2 = 3, their volume is 2 + 2 = 4, and their value is 6 + 9 = 15. Picking items[0] and items[3] would give value 16 with weight 4, but their volume is 5, which is more than 4.

02 · Example 2
FastPrep Pro
Reported in 1 Google interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 2 more worked examples, explained
  • Guided hints and editorial
  • Run your code on real test cases
$8.25/month

$99 billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week
All Google interview questionsSee Google hiring insights
CodePython 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import heapq
from collections import defaultdict
 
class Solution:
def solve(self, values, queries):
# Build the adjacency structure
n = len(values)
graph = defaultdict(list)
for u, v in queries:
graph[u].append(v)
 
best = [float("inf")] * n
heap = [(0, 0)]
while heap:
cost, node = heapq.heappop(heap)
if cost > best[node]:
continue
Run and Submit unlock with Pro
FastPrep Pro
Reported in 1 Google interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 2 more worked examples, explained
  • Guided hints and editorial
  • Run your code on real test cases
$8.25/month

$99 billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week