Dynamic Stack Using Resizable Array in DSA Javascript - 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 this dynamic stack push operation.
class DynamicStack {
constructor() {
this.array = new Array(2);
this.size = 0;
}
push(value) {
if (this.size === this.array.length) {
this.resize();
}
this.array[this.size] = value;
this.size++;
}
resize() {
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 code adds items to a stack. When the array is full, it doubles its size by copying items to a bigger array.
Look at what repeats when pushing items.
- Primary operation: Copying all items during resize.
- How many times: Resizing happens only when the array is full, so copying happens less often as size grows.
Most pushes just add an item quickly. Occasionally, resizing copies all items, which takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 simple adds + 3 copies during resizes |
| 100 | About 100 simple adds + 7 copies during resizes |
| 1000 | About 1000 simple adds + 10 copies during resizes |
Pattern observation: Most operations are quick, and copying happens rarely, so average time per push stays low.
Time Complexity: O(1) amortized
This means each push usually takes the same short time, even though resizing sometimes takes longer.
[X] Wrong: "Every push takes a long time because of resizing."
[OK] Correct: Resizing happens only occasionally, so most pushes are very fast, making the average time low.
Understanding amortized time helps you explain why dynamic arrays and stacks are efficient in real programs.
"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-size array stack limitation
A fixed-size array stack has a set capacity and cannot grow beyond it, causing overflow if exceeded.Step 2: Understand dynamic stack advantage
A dynamic stack using a resizable array can increase its capacity automatically when full, allowing more elements without overflow.Final Answer:
It can grow or shrink automatically as elements are added or removed. -> Option DQuick Check:
Dynamic resizing = automatic growth/shrink [OK]
- Thinking dynamic stack uses less memory always
- Assuming fixed capacity avoids resizing overhead
- Believing dynamic stack disallows duplicates
Solution
Step 1: Understand array resizing in JavaScript
JavaScript arrays are dynamic but to simulate resizing, we create a new larger array and copy elements.Step 2: Analyze options for doubling size
this.array = [...this.array, ...new Array(this.array.length)]; uses spread operator to copy existing elements and adds a new array of same length, effectively doubling size.Final Answer:
this.array = [...this.array, ...new Array(this.array.length)]; -> Option BQuick Check:
Spread operator copies + new array doubles size [OK]
- Setting length to length + 1 only increases size by 1, not doubling
- Using push with array adds nested array, not size
- Creating new array without copying loses data
class DynamicStack {
constructor() {
this.array = [];
this.top = -1;
}
push(value) {
if (this.top + 1 === this.array.length) {
this.array = [...this.array, ...new Array(this.array.length || 1)];
}
this.top++;
this.array[this.top] = value;
}
}
const stack = new DynamicStack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.array.slice(0, stack.top + 1));
What is the output?Solution
Step 1: Trace push operations and resizing
Initially array is empty. First push adds 10, array resizes to length 1 (from 0), then 10 stored at index 0. Second push resizes array from length 1 to 2, adds 20 at index 1. Third push resizes from 2 to 4, adds 30 at index 2.Step 2: Slice array up to top index + 1
top is 2 after three pushes, so slice(0, 3) returns [10, 20, 30]. Extra undefined elements are beyond slice range.Final Answer:
[10, 20, 30] -> Option CQuick Check:
Slice array to top+1 = [10, 20, 30] [OK]
- Expecting undefined elements in output
- Confusing array length with number of elements
- Not updating top index correctly
pop() {
if (this.top === -1) {
return null;
}
const value = this.array[this.top];
this.array[this.top] = undefined;
this.top--;
if (this.top < this.array.length / 4) {
this.array.length = Math.floor(this.array.length / 2);
}
return value;
}
What is the bug in this pop method?Solution
Step 1: Understand array shrinking logic
The code shrinks the array length when top is less than quarter of array length.Step 2: Identify problem with direct length reduction
Reducing array length directly truncates elements beyond new length, which may include valid stack elements if top is not updated properly.Final Answer:
Reducing array length directly may remove elements still in use. -> Option AQuick Check:
Direct length cut risks losing valid elements [OK]
- Ignoring empty stack check
- Not decrementing top index
- Assuming array never shrinks
Solution
Step 1: Understand resizing requirements
Doubling and halving array size requires creating new arrays to avoid losing elements.Step 2: Analyze resizing methods
Create a new array of the new size and copy existing elements before replacing the old array. copies elements to a new array of correct size, preserving stack data safely.Step 3: Why other options fail
Directly set the array length property to new size to resize the array. truncates or extends array without copying, losing data. Use array.push() to add undefined elements to increase size and pop() to reduce size. misuses push/pop for resizing. Do not resize the array; just keep track of top index. ignores resizing.Final Answer:
Create a new array of the new size and copy existing elements before replacing the old array. -> Option AQuick Check:
Copy elements to new array for safe resizing [OK]
- Setting length property directly to resize
- Using push/pop to resize array
- Ignoring resizing and risking overflow
Ready to prove it?
Pass the test and this pattern moves unknown
