Skip to content
  • Courses
  • Resources
  • Blog
  • About
Menu
  • Courses
  • Resources
  • Blog
  • About
STUDENT LOGIN
  • Courses
  • Resources
  • Blog
  • About
  • Student Login
Menu
  • Courses
  • Resources
  • Blog
  • About
  • Student Login

Coding Interview Question: 0-1 Knapsack

  • June 19, 2017

0-1 Knapsack: Coding Interview Question

Question

Given a list of items with values and weights, as well as a max weight, find the maximum value you can generate from items where the sum of the weights is less than the max.

eg.

1
2
3
items = {(w:1, v:6), (w:2, v:10), (w:3, v:12)}
maxWeight = 5
knapsack(items, maxWeight) = 22

Once you think that you’ve solved the problem, click below to see the solution.

 

As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.


Solution

How was that problem? You can check out the solution in the video below.

Here is the source code for the solution shown in the video (Github):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Item class
public static class Item {
    int weight;
    int value;
        
    public Item(int weight, int value) {
        this.weight = weight;
        this.value = value;
    }
}
    
// Recursively check every combination of items by traversing list of items
// and either including or excluding each item
public static int naiveKnapsack(Item[] items, int W) {
    return naiveKnapsack(items, W, 0);
}
    
// Overloaded recursive function for naiveKnapsack
private static int naiveKnapsack(Item[] items, int W, int i) {
    // Return when we reach the end of the list
    if (i == items.length) return 0;
        
    // If item is heavier than remaining weight, skip item
    if (W - items[i].weight < 0) return naiveKnapsack(items, W, i+1);
        
    // Try both including and excluding the current item
    return Math.max(naiveKnapsack(items, W - items[i].weight, i+1) + items[i].value,
                    naiveKnapsack(items, W, i+1));
}
    
// Recursive solution that uses a cache to improve performance
public static int topDownKnapsack(Item[] items, int W) {
    // Map: i -> W -> value
    // Use a map instead of array because the data could be very sparse
    Map<Integer, Map<Integer, Integer>> cache = new HashMap<Integer, Map<Integer, Integer>>();
    return topDownKnapsack(items, W, 0, cache);
}
    
// Overloaded recursive function for topDownKnapsack
private static int topDownKnapsack(Item[] items, int W, int i, Map<Integer, Map<Integer, Integer>> cache) {
    // Return when we reach the end of the list
    if (i == items.length) return 0;
        
    // Check the cache and return value if we get a hit
    if (!cache.containsKey(i)) cache.put(i, new HashMap<Integer, Integer>());
    Integer cached = cache.get(i).get(W);
    if (cached != null) return cached;
        
    // If item is heavier than remaining weight, skip item
    if (W - items[i].weight < 0) return topDownKnapsack(items, W, i+1, cache);
    
    // Try both including and excluding the current item
    int toReturn = Math.max(topDownKnapsack(items, W - items[i].weight, i+1, cache) + items[i].value,
                            topDownKnapsack(items, W, i+1, cache));
    cache.get(i).put(W, toReturn);
    return toReturn;
}
    
// Iterative dynamic programming solution
public static int bottomUpKnapsack(Item[] items, int W) {
    // cache[i][j] = max value for the first i items with a max weight of j
    int[][] cache = new int[items.length + 1][W + 1];
    for (int i = 1; i <= items.length; i++) {
        for (int j = 0; j <= W; j++) {
            // If including item[i-1] would exceed max weight j, don't
            // include the item. Otherwise take the max value of including
            // or excluding the item
            if (items[i-1].weight > j) cache[i][j] = cache[i-1][j];
            else cache[i][j] = Math.max(cache[i-1][j], cache[i-1][j-items[i-1].weight] + items[i-1].value);
        }
    }
        
    return cache[items.length][W];
}

Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.

DON'T DO ANOTHER CODING INTERVIEW...

...until you've mastered these 50 questions!

GET YOUR FREE GUIDE

RECOMMENDED ARTICLES

data structures

Article

The Definitive Guide to Data Structures for Coding Interviews

Data structures are critical to coding interview success. In this post, I'll show you exactly which data structures you need to know to nail your interviews.

Article

Acing the Google Interview: The Ultimate Guide

Acing the Google interview. Every engineer's dream. But the Google interview is really hard. In this post, you'll learn exactly how to prepare effectively.
stuck on coding interview

Article

10 ways to get unstuck and never fail another coding interview

It happens time and again. People fail coding interviews because they don’t know what to do when stuck on a problem. Developing a clear plan of attack helps you to succeed at any whiteboard coding interview.
Envelope Twitter Facebook Linkedin Youtube

© Byte by Byte 2016-2022

Privacy Policy

Terms and Conditions

Earnings Disclaimer

What if coding interviews were easy?

Sounds impossible right? It’s not!

Let me show you the RIGHT way to study for interviews so you can ace your Google Interview without breaking a sweat.

Download my FREE guide to the 50 most common coding interview questions asked at companies like Google, Facebooks, and Amazon.

Download my FREE guide to the 50 most common coding interview questions asked at companies like Google, Facebooks, and Amazon.

Get fully prepared for your Coding Interview and save 20% with Exponent. Learn More  →