Dynamic Stack Using Resizable Array in DSA Typescript - Time & Space Complexity
We want to understand how fast operations like push and pop work in a dynamic stack that grows as needed.
How does the time to add or remove items change as the stack gets bigger?
Analyze the time complexity of the following code snippet.
class DynamicStack {
private arr: number[] = [];
private capacity: number = 2;
private top: number = -1;
push(value: number): void {
if (this.top + 1 === this.capacity) {
this.capacity *= 2;
const newArr = new Array(this.capacity);
for (let i = 0; i <= this.top; i++) {
newArr[i] = this.arr[i];
}
this.arr = newArr;
}
this.arr[++this.top] = value;
}
pop(): number | undefined {
if (this.top === -1) return undefined;
return this.arr[this.top--];
}
}
This code shows a stack that doubles its array size when full, copying old elements to a bigger array before adding new ones.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying all elements to a new larger array when resizing.
- How many times: This copying happens only when the array is full, which occurs after doubling the capacity each time.
- Other operations: Push and pop themselves are simple and happen once per call.
Most push operations just add an item quickly, but occasionally the stack must copy all items to a bigger array.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 simple pushes + 8 copies during resizes |
| 100 | About 100 simple pushes + 196 copies during resizes |
| 1000 | About 1000 simple pushes + 2044 copies during resizes |
Pattern observation: Most pushes are fast, but copying happens less often as the stack grows, spreading the cost over many pushes.
Time Complexity: O(1) amortized
This means each push usually takes constant time, but sometimes takes longer when resizing, yet averaged out it stays fast.
[X] Wrong: "Every push takes a long time because of copying."
[OK] Correct: Copying happens only occasionally when the array is full, so most pushes are quick and the average time stays low.
Understanding amortized time helps you explain why dynamic arrays and stacks are efficient in real programs, showing you know how data structures handle growth smoothly.
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 size and cannot grow beyond it, limiting capacity.Step 2: Understand dynamic resizing
A dynamic stack with resizable array can increase or decrease its size during runtime to fit more or fewer elements.Final Answer:
It can grow or shrink in size as needed during runtime. -> Option AQuick Check:
Dynamic resizing = flexible size [OK]
- Thinking dynamic stack has fixed max size
- Confusing memory use with linked list
- Assuming no resizing needed
Solution
Step 1: Understand resizing by copying
To resize, create a new larger array and copy existing elements into it.Step 2: Check each option
A uses spread but adds empty elements, not doubling size properly; B creates new array, copies elements, then replaces original array; C only changes length property but does not copy elements; D pushes empty elements, not resizing properly.Final Answer:
const newArray = new Array(this.array.length * 2); for(let i=0; i -> Option DQuick Check:
Copy elements to new larger array = B [OK]
- Only changing length without copying
- Using push to resize array
- Adding empty elements without copying
push(value: number) {
if (this.size === this.array.length) {
const newArray = new Array(this.array.length * 2);
for (let i = 0; i < this.array.length; i++) {
newArray[i] = this.array[i];
}
this.array = newArray;
}
this.array[this.size] = value;
this.size++;
}
If the initial array length is 2 and we push 3 elements: 10, 20, 30, what is the internal array state after these pushes?Solution
Step 1: Trace initial array and pushes
Initial array length is 2, so after pushing 10 and 20, array is full.Step 2: On pushing 30, array resizes to length 4 and copies elements 10, 20.
Then 30 is added at index 2, size becomes 3.Final Answer:
[10, 20, 30, undefined] -> Option AQuick Check:
Resize doubles length, elements copied, new slot added [OK]
- Forgetting to resize before adding third element
- Assuming array length stays 2
- Confusing undefined with 0
pop(): number | undefined {
if (this.size === 0) return undefined;
this.size--;
const value = this.array[this.size];
this.array[this.size] = undefined;
if (this.size > 0 && this.size === Math.floor(this.array.length / 4)) {
const newArray = new Array(Math.floor(this.array.length / 2));
for (let i = 0; i < this.size; i++) {
newArray[i] = this.array[i];
}
this.array = newArray;
}
return value;
}
What is the bug in this code?Solution
Step 1: Analyze order of operations
The code sets this.array[this.size] = undefined before copying elements to newArray.Step 2: Understand effect on copying
When copying, the popped element is already undefined, so data is lost if resizing happens now.Final Answer:
It sets popped element to undefined before copying, losing data. -> Option BQuick Check:
Clear after copying to avoid data loss [OK]
- Ignoring order of clearing and copying
- Shrinking array too often is not the main bug here
- Missing empty stack check is false here
Solution
Step 1: Understand resizing conditions
Doubling on push when full is standard. Halving on pop should avoid frequent resizing.Step 2: Avoid frequent resizing by checking size and minimum capacity
Only halve when size is less than one-quarter and array length is above initial capacity to prevent shrinking too small.Final Answer:
Resize array to double size on push when full, and halve size on pop only when size is less than one-quarter of array length and array length is greater than initial capacity. -> Option CQuick Check:
Resize carefully to avoid thrashing [OK]
- Shrinking too early causing many resizes
- Shrinking when size equals one-quarter causing thrashing
- Shrinking below initial capacity
Ready to prove it?
Pass the test and this pattern moves unknown
