Modifying arrays in Javascript - Time & Space Complexity
When we change items in an array, the time it takes can grow as the array gets bigger.
We want to know how the work needed changes when we add or remove items.
Analyze the time complexity of the following code snippet.
const arr = [1, 2, 3, 4, 5];
// Add an item at the end
arr.push(6);
// Remove the first item
arr.shift();
// Insert an item at index 2
arr.splice(2, 0, 10);
This code adds, removes, and inserts items in an array at different positions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Moving elements to make space or close gaps when inserting or removing.
- How many times: Depends on how many elements need to shift after the change.
When adding at the end, work stays about the same no matter the size.
When removing or inserting near the start, many elements must move, so work grows with array size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Few to 10 moves |
| 100 | Few to 100 moves |
| 1000 | Few to 1000 moves |
Pattern observation: Inserting or removing at the start or middle means more moves as array grows; adding at the end stays quick.
Time Complexity: O(n)
This means the time to insert or remove items can grow directly with the number of elements in the array.
[X] Wrong: "Adding or removing items anywhere in an array always takes the same time."
[OK] Correct: Removing or inserting at the start or middle requires shifting many elements, so it takes longer as the array grows.
Understanding how array changes affect time helps you explain your code choices clearly and shows you know how data structures work behind the scenes.
"What if we used a linked list instead of an array? How would the time complexity for inserting or removing items change?"