Bird
Raised Fist0
DSA Javaprogramming

Dynamic Stack Using Resizable Array in DSA Java

Choose your learning style10 modes available
Mental Model
A stack stores items in order, and when it fills up, it grows bigger automatically to hold more items.
Analogy: Imagine a stack of plates that can magically get a bigger base when more plates are added so it never falls over.
Stack array: [1, 2, 3, null, null]
Top points here: ↑ (index 2)
Dry Run Walkthrough
Input: Push values 1, 2, 3, 4, 5 into a stack with initial capacity 3
Goal: Show how the stack grows when capacity is reached and all values are stored correctly
Step 1: Push 1 onto stack
[1, null, null] ↑top=0
Why: Add first item at index 0, top moves to 0
Step 2: Push 2 onto stack
[1, 2, null] ↑top=1
Why: Add second item at index 1, top moves to 1
Step 3: Push 3 onto stack
[1, 2, 3] ↑top=2
Why: Add third item at index 2, top moves to 2
Step 4: Push 4 triggers resize, double capacity to 6
[1, 2, 3, null, null, null] ↑top=2
Why: Array full, create bigger array and copy old items
Step 5: Add 4 after resize
[1, 2, 3, 4, null, null] ↑top=3
Why: Add new item at index 3, top moves to 3
Step 6: Push 5 onto stack
[1, 2, 3, 4, 5, null] ↑top=4
Why: Add item at index 4, top moves to 4
Result:
[1, 2, 3, 4, 5, null] ↑top=4
Annotated Code
DSA Java
public class DynamicStack {
    private int[] stack;
    private int top;

    public DynamicStack(int capacity) {
        stack = new int[capacity];
        top = -1;
    }

    public void push(int value) {
        if (top == stack.length - 1) {
            resize();
        }
        top++;
        stack[top] = value;
    }

    private void resize() {
        int newCapacity = stack.length * 2;
        int[] newStack = new int[newCapacity];
        for (int i = 0; i < stack.length; i++) {
            newStack[i] = stack[i];
        }
        stack = newStack;
    }

    public int pop() {
        if (top == -1) {
            throw new RuntimeException("Stack is empty");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public String toString() {
        if (top == -1) return "Stack is empty";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <= top; i++) {
            sb.append(stack[i]);
            if (i != top) sb.append(" -> ");
        }
        sb.append(" -> null");
        return sb.toString();
    }

    public static void main(String[] args) {
        DynamicStack ds = new DynamicStack(3);
        ds.push(1);
        ds.push(2);
        ds.push(3);
        ds.push(4);
        ds.push(5);
        System.out.println(ds);
    }
}
if (top == stack.length - 1) { resize(); }
Check if stack is full and resize array if needed
top++; stack[top] = value;
Move top pointer up and add new value
int newCapacity = stack.length * 2; int[] newStack = new int[newCapacity]; for (int i = 0; i < stack.length; i++) { newStack[i] = stack[i]; } stack = newStack;
Create bigger array and copy old values to it
OutputSuccess
1 -> 2 -> 3 -> 4 -> 5 -> null
Complexity Analysis
Time: O(n) for resizing when capacity is reached because all elements are copied; O(1) amortized for push otherwise
Space: O(n) because the array size grows with the number of elements
vs Alternative: Compared to fixed-size stack, dynamic stack avoids overflow by resizing but uses extra time during resize
Edge Cases
Push on empty stack
Works normally, adds first element at index 0
DSA Java
top++;
stack[top] = value;
Push when stack is full
Triggers resize to double capacity before adding new element
DSA Java
if (top == stack.length - 1) { resize(); }
Pop from empty stack
Throws RuntimeException with message 'Stack is empty'
DSA Java
if (top == -1) { throw new RuntimeException("Stack is empty"); }
When to Use This Pattern
When you need a stack that can grow beyond a fixed size without errors, use a dynamic stack with resizing to handle unknown or large input sizes safely.
Common Mistakes
Mistake: Not resizing the array when full, causing index out of bounds errors
Fix: Add a resize method and call it before pushing when the array is full
Mistake: Forgetting to increment top before adding the new element
Fix: Always increment top first, then assign the value at stack[top]
Summary
Stores items in a stack that grows automatically when full.
Use when you want a stack without a fixed size limit.
The key is to double the array size and copy items when capacity is reached.

Practice

(1/5)
1. What is the main advantage of using a dynamic stack implemented with a resizable array compared to a fixed-size array stack?
easy
A. It can grow or shrink automatically as elements are pushed or popped.
B. It uses less memory than a linked list stack.
C. It does not require any resizing operations.
D. It always has a fixed maximum size.

Solution

  1. Step 1: Understand fixed-size array stack limitation

    A fixed-size array stack has a maximum capacity that cannot change, so it can overflow if too many elements are pushed.
  2. Step 2: Understand dynamic stack resizing

    A dynamic stack using a resizable array can increase or decrease its size automatically when needed, avoiding overflow and wasting less memory.
  3. Final Answer:

    It can grow or shrink automatically as elements are pushed or popped. -> Option A
  4. Quick Check:

    Dynamic resizing = automatic growth/shrink [OK]
Hint: Dynamic stack resizes array automatically on overflow or underflow [OK]
Common Mistakes:
  • Thinking dynamic stack never resizes
  • Confusing dynamic stack with linked list stack
  • Assuming fixed size means dynamic resizing
2. Which of the following Java code snippets correctly doubles the size of the internal array when the stack is full?
easy
A. if (top == arr.length) { arr = Arrays.copyOf(arr, arr.length * 2); }
B. if (top > arr.length) { arr = Arrays.copyOf(arr, arr.length / 2); }
C. if (top == arr.length) { arr = Arrays.copyOf(arr, arr.length / 2); }
D. if (top < arr.length) { arr = Arrays.copyOf(arr, arr.length * 2); }

Solution

  1. Step 1: Check condition for resizing

    The array should resize when the stack is full, i.e., when top equals array length.
  2. Step 2: Check resizing operation

    The array size should double to accommodate more elements, so new size is arr.length * 2.
  3. Final Answer:

    if (top == arr.length) { arr = Arrays.copyOf(arr, arr.length * 2); } -> Option A
  4. Quick Check:

    Resize when full, double size [OK]
Hint: Resize when top == length, double array size [OK]
Common Mistakes:
  • Resizing when top > length (impossible)
  • Shrinking array instead of doubling
  • Resizing when array not full
3. Consider the following Java code for a dynamic stack using a resizable array:
DynamicStack stack = new DynamicStack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.pop();
stack.push(40);
stack.push(50);
System.out.println(stack);

What will be the printed output if the stack's toString method prints elements from bottom to top separated by ' -> ' and ends with ' -> null'?
medium
A. 50 -> 40 -> 20 -> 10 -> null
B. 10 -> 20 -> 30 -> 40 -> 50 -> null
C. 10 -> 20 -> null
D. 10 -> 20 -> 40 -> 50 -> null

Solution

  1. Step 1: Trace push and pop operations

    Push 10, 20, 30: stack = [10, 20, 30]
    Pop removes 30: stack = [10, 20]
    Push 40, 50: stack = [10, 20, 40, 50]
  2. Step 2: Understand toString output

    Prints from bottom to top separated by ' -> ' ending with ' -> null'. So output is "10 -> 20 -> 40 -> 50 -> null".
  3. Final Answer:

    10 -> 20 -> 40 -> 50 -> null -> Option D
  4. Quick Check:

    Stack after operations = 10,20,40,50 [OK]
Hint: Track push/pop stepwise, print bottom to top [OK]
Common Mistakes:
  • Forgetting pop removes last pushed element
  • Printing top to bottom instead of bottom to top
  • Including popped element in output
4. The following Java method is part of a dynamic stack implementation. It is supposed to pop an element and shrink the array size by half when the number of elements is less than a quarter of the array length. Identify the bug:
public int pop() {
    if (top == 0) throw new EmptyStackException();
    int val = arr[--top];
    if (top < arr.length / 4) {
        arr = Arrays.copyOf(arr, arr.length / 2);
    }
    return val;
}
medium
A. The pop method does not decrement top before accessing arr.
B. Shrinking array without checking minimum size can cause array size zero.
C. The condition should be top > arr.length / 4 to shrink.
D. The method should double the array size instead of halving it.

Solution

  1. Step 1: Analyze shrinking condition and operation

    The array shrinks when top < arr.length / 4 by halving the array size.
  2. Step 2: Identify potential bug

    If array size is small (like 1 or 2), halving repeatedly can reduce array size to zero, causing errors on next push/pop.
  3. Final Answer:

    Shrinking array without checking minimum size can cause array size zero. -> Option B
  4. Quick Check:

    Check minimum array size before shrinking [OK]
Hint: Always check minimum array size before shrinking [OK]
Common Mistakes:
  • Not checking for empty stack before pop
  • Wrong condition for shrinking
  • Shrinking array too small causing errors
5. You want to implement a dynamic stack using a resizable array that doubles its size when full and halves its size when the number of elements falls below one-fourth of the array length, but never shrinks below a minimum capacity of 4. Which of the following code snippets correctly implements the pop method with this behavior?
public int pop() {
    if (top == 0) throw new EmptyStackException();
    int val = arr[--top];
    if (top < arr.length / 4 && arr.length > 4) {
        arr = Arrays.copyOf(arr, Math.max(arr.length / 2, 4));
    }
    return val;
}
hard
A. Does not shrink array at all.
B. Shrinks array below size 4 causing errors.
C. Correctly shrinks array but never below size 4.
D. Doubles array size on pop instead of shrinking.

Solution

  1. Step 1: Check shrinking condition and minimum size

    The code shrinks array only if top < arr.length / 4 and arr.length > 4, ensuring minimum size 4.
  2. Step 2: Verify shrinking operation

    Uses Math.max(arr.length / 2, 4) to avoid shrinking below 4, preventing errors.
  3. Final Answer:

    Correctly shrinks array but never below size 4. -> Option C
  4. Quick Check:

    Shrink with minimum size check = correct pop method [OK]
Hint: Use Math.max to enforce minimum array size when shrinking [OK]
Common Mistakes:
  • Shrinking array below minimum size
  • Not shrinking array when needed
  • Incorrect condition for shrinking
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard