Consider a dynamic stack implemented using a resizable array. The stack doubles its capacity when full.
Starting with an empty stack of capacity 2, perform these operations:
Push(10)
Push(20)
Push(30)
Pop()
Push(40)
What is the printed stack content from top to bottom?
class DynamicStack { private int[] arr = new int[2]; private int top = -1; public void Push(int val) { if (top == arr.Length - 1) { int[] newArr = new int[arr.Length * 2]; for (int i = 0; i < arr.Length; i++) newArr[i] = arr[i]; arr = newArr; } arr[++top] = val; } public int Pop() { if (top == -1) throw new InvalidOperationException("Stack empty"); return arr[top--]; } public override string ToString() { if (top == -1) return "Stack is empty"; string s = ""; for (int i = top; i >= 0; i--) s += arr[i] + " -> "; return s + "null"; } } var stack = new DynamicStack(); stack.Push(10); stack.Push(20); stack.Push(30); stack.Pop(); stack.Push(40); Console.WriteLine(stack.ToString());
Remember the stack grows and shrinks. The top is the last pushed item not popped.
After pushing 10, 20, 30, the stack is [10, 20, 30]. Popping removes 30. Then pushing 40 adds it on top. So stack is [10, 20, 40] with 40 on top.
In a dynamic stack using a resizable array, what is the typical behavior when the internal array is full and a new element is pushed?
Think about how dynamic arrays grow to accommodate more elements.
When the array is full, the stack creates a new array twice as big, copies all elements, then adds the new element. This avoids overflow.
Given this Pop method in a dynamic stack, what is the bug?
public int Pop() {
if (top == 0) throw new InvalidOperationException("Stack empty");
return arr[top--];
}Think about how the top index is initialized and what value means empty.
Top starts at -1 when empty. Checking 'top == 0' misses empty state and causes errors when popping from empty stack.
Starting with an empty dynamic stack with initial capacity 1, what is the capacity after pushing these elements?
Push(5)
Push(10)
Push(15)
Push(20)
class DynamicStack { private int[] arr = new int[1]; private int top = -1; public void Push(int val) { if (top == arr.Length - 1) { int[] newArr = new int[arr.Length * 2]; for (int i = 0; i < arr.Length; i++) newArr[i] = arr[i]; arr = newArr; } arr[++top] = val; } public int Capacity() { return arr.Length; } } var stack = new DynamicStack(); stack.Push(5); stack.Push(10); stack.Push(15); stack.Push(20); Console.WriteLine(stack.Capacity());
Remember the array doubles capacity when full.
Initial capacity 1 doubles to 2 after first push fills it, then doubles to 4 after pushing third element. So capacity is 4 after 4 pushes.
Why do we use dynamic resizing (like doubling array size) in stack implementations using arrays?
Think about balancing memory use and ability to add many elements.
Dynamic resizing allows the stack to grow as needed without fixed limits, while keeping push operations efficient by doubling size only when full.
