0
0
Javascriptprogramming~5 mins

Common array operations in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Common array operations
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Searching through the array with includes and shifting elements with shift.
  • How many times: includes checks each element until it finds a match or reaches the end; shift moves all elements one step forward.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10Push: 1, Includes: up to 10, Shift: up to 9
100Push: 1, Includes: up to 100, Shift: up to 99
1000Push: 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.

Final Time Complexity

Time Complexity: O(n)

This means the time to search or remove from the front grows roughly in direct proportion to the array size.

Common Mistake

[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.

Interview Connect

Understanding how common array operations scale helps you write efficient code and explain your choices clearly in interviews.

Self-Check

"What if we used a linked list instead of an array? How would the time complexity of removing the first item change?"