Module 1 · Lesson 1 · ~20 min

Arrays under the hood

You've used arrays a thousand times. So why do interviewers keep asking about them? Because somewhere between "I push to a list" and "this loop is suddenly O(n²)" there's a memory model nobody told you about. Once you can see what the hardware sees, you'll stop accidentally writing slow code without knowing why.

The trick that makes arr[i] instant

An array is a single contiguous block of memory holding fixed-size slots. To find slot i, the CPU does one multiplication: base_address + i × element_size. No searching. No looping. One arithmetic op and a memory fetch. That's why random access is O(1) — and it's the property every other behavior of arrays follows from.

Languages dress this up differently:

LanguageWhat "array" actually isWhat each slot holds
C / C++ std::vectorcontiguous block of element bytesthe value itself
Python listcontiguous block of pointersa pointer to a heap-allocated PyObject
JavaScript Arraycontiguous (mostly) — V8 has multiple backing modes; sparse arrays fall back to a hasha tagged value or a pointer
Java ArrayListcontiguous block of referencesa reference to a heap-allocated object

This matters because Python and Java arrays already require two memory hops per access (load pointer, dereference). C arrays of primitives need one. That's why "Python is slow" — the language model is doing more work per access, even before we measure cache effects.

Visualize the operations

Here's what the array looks like across common operations. Watch carefully — the work matches the Big-O.

The full operation table

OperationCostWhy
Access by index arr[i]O(1)One address computation.
Set by index arr[i] = xO(1)Same.
LengthO(1)Stored as metadata, not computed.
Linear searchO(n)Worst case: scan every element.
Append (push to end)amortized O(1)Reallocate-and-copy on capacity overflow; the copies sum to a constant amortized per push.
Pop from endO(1)Decrement length, no shifting.
Insert at front / middleO(n)Every element after the insert point shifts right by one.
Pop from front / middleO(n)Every element after the removal shifts left by one.
Slicing arr[i:j] (Python/JS)O(j − i)It copies. Easy to forget — interviewers love when candidates miss this.
The slicing trap

In Python, arr[1:] in a loop body is a quiet O(n²) bomb. Same in JS with arr.slice(1). Use indices instead — the array doesn't care which index you call "the start."

The patterns that show up everywhere

1. Walk-and-track

You scan the array left-to-right, maintaining a tiny piece of state — the running sum, the running max, the index of the previous occurrence. O(n) time, O(1) space. Maximum subarray (Kadane's), best time to buy/sell stock, all variants of "find the first/last/largest such-that" — all walk-and-track.

# Best time to buy and sell stock — walk-and-track
def max_profit(prices):
    best_buy = float('inf')
    best_profit = 0
    for p in prices:
        best_buy = min(best_buy, p)
        best_profit = max(best_profit, p - best_buy)
    return best_profit
# O(n) time, O(1) space
// Best time to buy and sell stock — walk-and-track
function maxProfit(prices) {
  let bestBuy = Infinity;
  let bestProfit = 0;
  for (const p of prices) {
    bestBuy = Math.min(bestBuy, p);
    bestProfit = Math.max(bestProfit, p - bestBuy);
  }
  return bestProfit;
}
// O(n) time, O(1) space
// Best time to buy and sell stock — walk-and-track
function maxProfit(prices: number[]): number {
  let bestBuy = Infinity;
  let bestProfit = 0;
  for (const p of prices) {
    bestBuy = Math.min(bestBuy, p);
    bestProfit = Math.max(bestProfit, p - bestBuy);
  }
  return bestProfit;
}
// O(n) time, O(1) space

2. Prefix sums

If you find yourself computing "sum from i to j" many times, build a prefix-sum array once. Then any range sum is O(1): prefix[j+1] - prefix[i].

def build_prefix(arr):
    p = [0]
    for x in arr:
        p.append(p[-1] + x)
    return p

# range_sum(i, j) = p[j+1] - p[i]   ← O(1) per query
function buildPrefix(arr) {
  const p = [0];
  for (const x of arr) p.push(p[p.length - 1] + x);
  return p;
}

// rangeSum(i, j) = p[j+1] - p[i]   ← O(1) per query
function buildPrefix(arr: number[]): number[] {
  const p: number[] = [0];
  for (const x of arr) p.push(p[p.length - 1] + x);
  return p;
}

// rangeSum(i, j) = p[j+1] - p[i]   ← O(1) per query
Pattern recognizer

Anytime the problem says "given many queries…" or "for each i, compute the sum/min/max of arr[i…j]," your first instinct should be a prefix structure. Range sums use prefix sums. Range mins/maxes use sparse tables or segment trees (rarely needed in interviews).

3. In-place reverse / rotate / partition

O(1) extra space tricks that the interviewer specifically is looking for. Reversing in place uses two pointers walking inward. Rotating an array by k can be done by reversing three sub-ranges.

def reverse_in_place(arr):
    i, j = 0, len(arr) - 1
    while i < j:
        arr[i], arr[j] = arr[j], arr[i]
        i += 1
        j -= 1
# O(n) time, O(1) space
function reverseInPlace(arr) {
  let i = 0, j = arr.length - 1;
  while (i < j) {
    [arr[i], arr[j]] = [arr[j], arr[i]];
    i++;
    j--;
  }
}
// O(n) time, O(1) space
function reverseInPlace(arr: number[]): void {
  let i = 0, j = arr.length - 1;
  while (i < j) {
    [arr[i], arr[j]] = [arr[j], arr[i]];
    i++;
    j--;
  }
}
// O(n) time, O(1) space

4. Sort first

If the operation gets cheaper after sorting, sort first. The O(n log n) cost is paid once and almost always worth it. Many "find the closest pair" or "find duplicates" problems are O(n²) without sorting and O(n log n) with.

Try it

Implement these from scratch. Each has a brute-force one-liner you could reach for; resist it and write the loop yourself — it's the muscle that matters.

def range_sums(arr, queries):
    # Build prefix once: prefix[k] = sum of arr[:k]
    prefix = [0]
    for x in arr:
        prefix.append(prefix[-1] + x)
    return [prefix[j + 1] - prefix[i] for i, j in queries]
  
function rangeSums(arr, queries) {
  const prefix = [0];
  for (const x of arr) prefix.push(prefix[prefix.length - 1] + x);
  return queries.map(([i, j]) => prefix[j + 1] - prefix[i]);
}
  
function rangeSums(arr: number[], queries: [number, number][]): number[] {
  const prefix = [0];
  for (const x of arr) prefix.push(prefix[prefix.length - 1] + x);
  return queries.map(([i, j]) => prefix[j + 1] - prefix[i]);
}
  
O(n + q) time, O(n) space. Build the prefix once (n adds); each query is O(1). The brute force (recompute each query) is O(q × n). The space is O(n) for the prefix array, irreducible if you want O(1)-per-query.

Notebook prompt