Common array operations in Javascript - Time & Space Complexity
When working with arrays, it is important to know how long common operations take as the array grows.
We want to understand how the time to do things like adding, searching, or removing items changes with array size.
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);
// Find an item
const found = arr.includes(3);
// Remove first item
arr.shift();
This code adds an item to the end, checks if an item exists, and removes the first item from the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching through the array with
includesand shifting elements withshift. - How many times:
includeschecks each element until it finds a match or reaches the end;shiftmoves all elements one step forward.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Push: 1, Includes: up to 10, Shift: up to 9 |
| 100 | Push: 1, Includes: up to 100, Shift: up to 99 |
| 1000 | Push: 1, Includes: up to 1000, Shift: up to 999 |
Pattern observation: Adding at the end stays quick, but searching and removing from the front take longer as the array grows.
Time Complexity: O(n)
This means the time to search or remove from the front grows roughly in direct proportion to the array size.
[X] Wrong: "Adding or removing items anywhere in the array always takes the same short time."
[OK] Correct: Adding at the end is fast, but removing from the front or searching requires checking or moving many items, so it takes longer as the array grows.
Understanding how common array operations scale helps you write efficient code and explain your choices clearly in interviews.
"What if we used a linked list instead of an array? How would the time complexity of removing the first item change?"