Question
Implement N > 0 stacks using a single array to store all stack data (you may use auxiliary arrays in your stack object, but all of the objects in all of the stacks must be in the same array). No stack should be full unless the entire array is full.
eg.
1 2 3 4 5 6 7 |
N = 3; capacity = 10; Stacks stacks = new Stacks(N, capacity); stacks.put(0, 10); stacks.put(2, 11); stacks.pop(0) = 10; stacks.pop(2) = 11; |
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:
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 |
public class Stacks { int[] topOfStack; int[] stackData; int[] nextIndex; int nextAvailable = 0; public Stacks(int numStacks, int capacity) { topOfStack = new int[numStacks]; for (int i = 0; i < topOfStack.length; i++) { topOfStack[i] = -1; } stackData = new int[capacity]; nextIndex = new int[capacity]; for (int i = 0; i < nextIndex.length - 1; i++) { nextIndex[i] = i+1; } nextIndex[nextIndex.length - 1] = -1; } public void push(int stack, int value) { if (stack < 0 || stack >= topOfStack.length) { throw new IndexOutOfBoundsException(); } if (nextAvailable < 0) return; int currentIndex = nextAvailable; nextAvailable = nextIndex[currentIndex]; stackData[currentIndex] = value; nextIndex[currentIndex] = topOfStack[stack]; topOfStack[stack] = currentIndex; } public int pop(int stack) { if (stack < 0 || stack >= topOfStack.length || topOfStack[stack] < 0) { throw new IndexOutOfBoundsException(); } int currentIndex = topOfStack[stack]; int value = stackData[currentIndex]; topOfStack[stack] = nextIndex[currentIndex]; nextIndex[currentIndex] = nextAvailable; nextAvailable = currentIndex; return value; } } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.