Dynamic Stack Using Resizable Array in DSA C++ - Time & Space Complexity
We want to understand how the time to add or remove items from a dynamic stack changes as the stack grows.
How does resizing the array affect the speed of stack operations?
Analyze the time complexity of the following code snippet.
class DynamicStack {
int* arr;
int capacity;
int topIndex;
void resize() {
int* newArr = new int[capacity * 2];
for (int i = 0; i < capacity; i++) {
newArr[i] = arr[i];
}
capacity *= 2;
delete[] arr;
arr = newArr;
}
void push(int val) {
if (topIndex == capacity) resize();
arr[topIndex++] = val;
}
int pop() {
return arr[--topIndex];
}
};
This code shows a stack that doubles its array size when full, allowing dynamic growth.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Pushing items and occasionally resizing the array.
- How many times: Each push usually adds one item; resizing happens less often but copies all current items.
Most pushes take a simple step, but when the array is full, resizing copies all items, which takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 simple pushes, 1 resize copying 10 items |
| 100 | About 100 pushes, 3 resizes copying 10, 20, 40 items |
| 1000 | About 1000 pushes, 7 resizes copying 10, 20, 40, 80, 160, 320, 640 items |
Pattern observation: Resizing happens rarely and copies all items, but most pushes are quick, so average work per push stays low.
Time Complexity: O(1) amortized
This means each push usually takes a quick step, and resizing cost spreads out over many pushes, keeping average time per push constant.
[X] Wrong: "Every push takes a long time because resizing copies all items."
[OK] Correct: Resizing happens only occasionally, so most pushes are fast. The copying cost is shared across many pushes, making average time low.
Understanding amortized time helps you explain why dynamic arrays and stacks are efficient in real programs, showing you grasp practical performance.
"What if we increased the array size by only 1 each time instead of doubling? How would the time complexity change?"
Practice
Solution
Step 1: Understand fixed vs dynamic size
A fixed-size array stack has a set capacity and cannot grow beyond it, causing overflow if exceeded.Step 2: Explain dynamic resizing
A dynamic stack using a resizable array automatically increases or decreases its size when needed, avoiding overflow and wasted space.Final Answer:
It can grow or shrink automatically as elements are pushed or popped. -> Option AQuick Check:
Dynamic resizing = automatic growth/shrink [OK]
- Thinking dynamic stack has fixed size
- Confusing memory use with linked list
- Assuming no resizing needed
Solution
Step 1: Identify array resizing in C++
For raw arrays,reallocis used to resize memory blocks dynamically.Step 2: Check each option
arr = new int[size * 2]; creates a new array but loses old data. arr.resize(size * 2); is for std::vector, not raw arrays. arr = (int*) realloc(arr, size * 2 * sizeof(int)); correctly usesreallocto resize preserving data. arr = arr * 2; is invalid syntax.Final Answer:
arr = (int*) realloc(arr, size * 2 * sizeof(int)); -> Option CQuick Check:
Raw array resize = realloc [OK]
- Using vector methods on raw arrays
- Creating new array without copying data
- Invalid pointer arithmetic
void push(int x) {
if (top == capacity) {
capacity *= 2;
arr = (int*) realloc(arr, capacity * sizeof(int));
}
arr[top++] = x;
}
// Initial capacity = 2, top = 0
push(10);
push(20);
push(30);
What is the value of capacity and the stack elements after these pushes?Solution
Step 1: Trace push calls and capacity changes
Initial capacity is 2. After pushing 10 and 20, top reaches 2 (full). On pushing 30, capacity doubles to 4, and 30 is added.Step 2: Confirm final stack and capacity
Stack elements are [10, 20, 30], capacity is 4 after resizing.Final Answer:
capacity = 4, stack = [10, 20, 30] -> Option BQuick Check:
Capacity doubles when full, stack holds all pushed elements [OK]
- Not doubling capacity before adding new element
- Assuming capacity equals number of elements
- Ignoring realloc effect
int pop() {
if (top == 0) {
throw "Stack Underflow";
}
int val = arr[--top];
if (top < capacity / 4) {
capacity /= 2;
arr = (int*) realloc(arr, capacity * sizeof(int));
}
return val;
}
What is the bug and how to fix it?Solution
Step 1: Analyze realloc usage
realloccan fail to allocate memory and return NULL, but the code does not check the return value before usingarr, which can lead to crashes.Step 2: Fix by checking realloc return
Store the result in a temporary pointer and check if it is NULL before assigning toarr. Handle the error case appropriately.Final Answer:
Bug: realloc is called without checking NULL; Fix: check realloc return. -> Option DQuick Check:
Always check realloc != NULL [OK]
- Ignoring minimum capacity limit
- Not decrementing top before access
- Not checking realloc NULL
int pop() {
if (top == 0) throw "Underflow";
int val = arr[--top];
if (top < capacity / 4 && capacity > 4) {
capacity /= 2;
arr = (int*) realloc(arr, capacity * sizeof(int));
}
return val;
}
What is the key reason for checking capacity > 4 before resizing?Solution
Step 1: Understand capacity shrinking condition
The stack shrinks when elements are less than one-fourth capacity, but must not shrink below initial capacity 4.Step 2: Explain importance of capacity > 4 check
This check prevents capacity from becoming less than 4, which avoids invalid memory allocation and potential errors.Final Answer:
To prevent the capacity from shrinking below the initial minimum size, avoiding invalid memory access. -> Option AQuick Check:
Minimum capacity check prevents invalid resize [OK]
- Shrinking capacity below initial size
- Ignoring memory safety on realloc
- Assuming performance reason only
Ready to prove it?
Pass the test and this pattern moves unknown
