Uploaded December 2018 | Updated September 2026, 2 weeks ago
Try Our Full Platform: nas.io/backtobackswe
📹 Intuitive Video Explanations
❓New Unseen Questions
🔎 Get All Solutions
I was inspired to do this video after seeing that Tuschar Roy had covered this problem. He did a good job, but I feel it very necessary to stress what is really happening and what each cell REALLY means.
Dynamic programming is about subproblems, not remembering patterns to fill cells in with. I watched EVERY ONE of Tuschar Roy's videos and found myself MEMORIZING how to fill out the cells INSTEAD of really knowing what was going on.
I hope this video sheds light on what this problem is really trying to express.
I talked about the bottom up way to do things. Here is the code for that way of doing it: sanfoundry.com/java-program-solve-knapsack-problem-using-dp
You can also do it TOP DOWN with recursion where we investigate all expressions of the subproblems to find the optimal solution. The book Elements of Programming Interviews by Aziz Adnan has a very good version of this. The problem is 17.6 in that book.
++++++++++++++++++++++++++++++++++++++++++++++++++
Question: Write a program for the knapsack problem that selects a subset of items that has maximum value and satisfies the weight constraint. All items have integer weights and values. Return the value of the subset.
Can we do it greedily?
0/1 means you cannot split an item. If you could split an item, you could solve this greedily by sorting the item entries by value and then picking from greatest value to least. When you run out of space in your "sack", you'd split the last item and then you would have maximized weight vs value.
Brute Force: We could consider all subsets of items in a complete search and take on the cost of exponential time of 2^n (we will explain this in another video).
Greedy doesn't work, brute forcing won't make the cut, now what? What can we do now?
Dynamic Programming.
Notice that we can subproblem this.
Dynamic programming is not about stupid magic tables that you see people fill out, it is not about guessing. DP is about remembering the solutions to subproblems so that we can find the globally optimal solution. We just subproblemed this recursively.
This is where the table comes from. Each cell MEANS SOMETHING.
IT IS THE ANSWER TO THE QUESTION.
If we solve all the subproblems and remember all answers then we will find the globally optimal answer.
The subproblems are represented by what is called a recurrence equation.
Complexities
n = total items
m = max weight (max weight constraint)
Time: O(nm) (we will be solving this many subproblems)
Space: O(nm) (we will store the results of n*m subproblems)
++++++++++++++++++++++++++++++++++++++++++++++++++
HackerRank: youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww
Tuschar Roy: youtube.com/user/tusharroy2525
GeeksForGeeks: youtube.com/channel/UC0RhatS1pyxInC00YKjjBqQ
Jarvis Johnson: youtube.com/user/VSympathyV
Success In Tech: youtube.com/channel/UC-vYrOAmtrx9sBzJAf3x_xw
++++++++++++++++++++++++++++++++++++++++++++
The 0/1 Knapsack problem is question 17.6 in the fantastic book Elements of Programming Interviews.
Try Our Full Platform: nas.io/backtobackswe
📹 Intuitive Video Explanations
❓New Unseen Questions
🔎 Get All Solutions
I was inspired to do this video after seeing that Tuschar Roy had covered this problem. He did a good job, but I feel it very necessary to stress what is really happening and what each cell REALLY means.
Dynamic programming is about subproblems, not remembering patterns to fill cells in with. I watched EVERY ONE of Tuschar Roy's videos and found myself MEMORIZING how to fill out the cells INSTEAD of really knowing what was going on.
I hope this video sheds light on what this problem is really trying to express.
I talked about the bottom up way to do things. Here is the code for that way of doing it: sanfoundry.com/java-program-solve-knapsack-problem-using-dp
You can also do it TOP DOWN with recursion where we investigate all expressions of the subproblems to find the optimal solution. The book Elements of Programming Interviews by Aziz Adnan has a very good version of this. The problem is 17.6 in that book.
++++++++++++++++++++++++++++++++++++++++++++++++++
Question: Write a program for the knapsack problem that selects a subset of items that has maximum value and satisfies the weight constraint. All items have integer weights and values. Return the value of the subset.
Can we do it greedily?
0/1 means you cannot split an item. If you could split an item, you could solve this greedily by sorting the item entries by value and then picking from greatest value to least. When you run out of space in your "sack", you'd split the last item and then you would have maximized weight vs value.
Brute Force: We could consider all subsets of items in a complete search and take on the cost of exponential time of 2^n (we will explain this in another video).
Greedy doesn't work, brute forcing won't make the cut, now what? What can we do now?
Dynamic Programming.
Notice that we can subproblem this.
Dynamic programming is not about stupid magic tables that you see people fill out, it is not about guessing. DP is about remembering the solutions to subproblems so that we can find the globally optimal solution. We just subproblemed this recursively.
This is where the table comes from. Each cell MEANS SOMETHING.
IT IS THE ANSWER TO THE QUESTION.
If we solve all the subproblems and remember all answers then we will find the globally optimal answer.
The subproblems are represented by what is called a recurrence equation.
Complexities
n = total items
m = max weight (max weight constraint)
Time: O(nm) (we will be solving this many subproblems)
Space: O(nm) (we will store the results of n*m subproblems)
++++++++++++++++++++++++++++++++++++++++++++++++++
HackerRank: youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww
Tuschar Roy: youtube.com/user/tusharroy2525
GeeksForGeeks: youtube.com/channel/UC0RhatS1pyxInC00YKjjBqQ
Jarvis Johnson: youtube.com/user/VSympathyV
Success In Tech: youtube.com/channel/UC-vYrOAmtrx9sBzJAf3x_xw
++++++++++++++++++++++++++++++++++++++++++++
The 0/1 Knapsack problem is question 17.6 in the fantastic book Elements of Programming Interviews.


![Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Free 5-Day Mini-Course: https://backtobackswe.com
Try Our Full Platform: https://backtobackswe.com/pricing
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions
Question: Write a program which takes as input a very long sequence of numbers and prints the numbers in sorted order. Each number is at most k away from its correctly sorted position. (Such an array is sometimes referred to as being k-sorted).
Pramp: https://www.pramp.com
Examples:
Input:
[ 3, -1, 2, 6, 4, 5 , 8 ]
k = 2
Each number is no more than 2 indices from its final sorted position.
Output:
[ -1, 2, 3, 4, 5, 6, 8 ]
It is often that data finds itself in an almost sorted state.
For example: A server needs to sort orders coming in internationally and due to differences in server loads and network routes some earlier orders come in after later orders.
How do we efficiently sort this almost sorted data?
Whenever I hear or think of sorting or searching, I think of my fast sorting algorithms, binary search, and min/max heaps.
Approach 1 (Brute Force)
Just run a quick sorting algorithm like mergesort or quicksort and have the array sorted in O( n * log(n) ) time.
This is an obvious answer.
The key insight we need to make is that most of the items are very close to their final positions and therefore we need to just “touch up” the order of the items.
How will we perform this “touch up”?
Approach 2 (Min Heap To The Rescue)
Example:
[ 3, -1, 2, 6, 4, 5, 8 ]
k = 2
How do I know who belongs at index 0?
Well, this leads me to ask you, what are the potentialities for each index? What items could be at index 0?
3 can, -1 can (if it moves 1 spot back), 2 can (if it moves 2 spots back), but 6 cannot (it would have to move 3 spots back but k = 2, this is not allowed).
Now our interest is in k + 1 items, 3, -1, and 2 each could go at index 0.
Our job is now reduced to finding the minimum of k + 1 elements at a time.
What data structure helps me with keeping track of minimums and maximums in a set of data very well?
A heap.
We will use a min heap because we want access to the smallest item across k + 1 items.
The Algorithm
Add the first k + 1 items to a min heap.
Iterate through every index in the array.
Place the min item and add the next item that has not been added yet to the heap.
When we cannot add un-added items to the heap near the end (at some point every item will have seen the heap but we will not be at the end of the iteration just yet) we can just continue ejecting and placing the min items.
Complexities
Time: O( n * log( k ) )
For all n items we will perform an insertion and removal from a min heap holding k + 1 items.
Space: O( k )
The heap will hold k + 1 numbers at maximum before an item is ejected.
++++++++++++++++++++++++++++++++++++++++++++++++++
HackerRank: https://www.youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww
Tuschar Roy: https://www.youtube.com/user/tusharroy2525
GeeksForGeeks: https://www.youtube.com/channel/UC0RhatS1pyxInC00YKjjBqQ
Jarvis Johnson: https://www.youtube.com/user/VSympathyV
Success In Tech: https://www.youtube.com/channel/UC-vYrOAmtrx9sBzJAf3x_xw
++++++++++++++++++++++++++++++++++++++++++++++++++
This question is 11.3 in the book Elements of Programming Interviews Sort A K Sorted Array - Investigating Applications of Min/Max Heaps](https://i.ytimg.com/vi/yQ84lk-EXTQ/mqdefault.jpg)