Sikau

Data structures · Day 2 · about 30 min

Arrays under the hood

Indexing, appending, inserting and removing — and what each costs.

Why is shift() slow?

An array stores items side by side in memory, so list[500] jumps straight to the right slot — O(1). But inserting at the front means moving every other item one place to the right. Knowing which operations are cheap tells you which data structure to pick.

The cost of each operation

const orders = [101, 102, 103, 104];

console.log(orders[2]);       // O(1) read by index
orders.push(105);             // O(1) append (amortised)
orders.pop();                 // O(1) remove from the end
orders.unshift(100);          // O(n) every item moves right
orders.shift();               // O(n) every item moves left
orders.splice(2, 0, 999);     // O(n) insert in the middle
console.log(orders.includes(104)); // O(n) search without an index
console.log(orders);

// Build the shifting yourself to see the work:
function insertAt(arr, index, value) {
  for (let i = arr.length; i > index; i--) arr[i] = arr[i - 1];
  arr[index] = value;
}
const a = [1, 2, 4];
insertAt(a, 2, 3);
console.log(a);

The rest of this lesson

  • Why push is cheapexplain
  • Removing without shiftingexplain
  • Cheap or expensive?predict
  • Cost on an arraymatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of Data structures