LESSON 01 / 04

Arrays Under the Hood

Why reading arr[i] is instant but inserting at the front is slow — and the in-place tricks interviewers love.

🎓Easylevel
⏱️35 minto finish
✏️2activities

📂 Arrays & Strings🏷️ Arrays

🎯 By the end of this lesson you can…

  • Explain how arrays sit in memory
  • Know the cost of common array operations
  • Modify arrays in place with a write pointer

A row of numbered seats

Array operation costs
OperationCostWhy
read / write arr[i]O(1)the address is computed directly
push / pop at the endO(1)*no shifting (*amortised)
insert / delete at the frontO(n)every item shifts
search for a valueO(n)may check every item
search in a sorted arrayO(log n)binary search

The write-pointer trick

Problem: remove every 0 from an array in place and return the new length.

remove-zeros.pseudo
1BEGIN2    SET NUMS = [0, 3, 0, 5, 7, 0]3    SET WRITE = 04    FOR READ = 0 TO LENGTH(NUMS) - 15        IF NUMS[READ] <> 0 THEN6            SET NUMS[WRITE] = NUMS[READ]7            SET WRITE = WRITE + 18        END IF9    END FOR10    DISPLAY WRITE11    DISPLAY NUMS12END

Remove a value in place

1function removeValue(nums, val) {2  let write = 0;3  for (let read = 0; read < nums.length; read++) {4    if (nums[read] !== val) nums[write++] = nums[read];5  }6  return write;7}8const a = [3, 2, 2, 3, 4];9const k = removeValue(a, 3);10console.log(k, a.slice(0, k));

✨ The logic didn’t change. Only the syntax changed.

💡 Concept check
Which operation is O(n) on an array?
🛠️ Move zeros to the end

Write moveZeros(nums) that moves all 0s to the end in place, keeping the order of the other numbers, and returns the array.

📌 Key takeaways

  • Access by index is O(1); search is O(n).
  • Insert/delete at the end is O(1); at the front or middle is O(n) (everything shifts).
  • The "write pointer" trick removes items in place in O(n) time, O(1) space.

Finished reading & practising?

Saved in this browser. Create a free account to keep it forever.