Notes
All notes

Arrays (DSA #2)

Give a computer a list of a million numbers and ask for the 500,000th. An array answers instantly, because it does not search — it computes. The 500,000th element sits at a fixed, predictable address, and finding it is one multiplication. That single property, contiguous memory with constant-time indexing, is why arrays are the default container and the benchmark every other structure is compared against.

This chapter covers how arrays are laid out, what each operation costs, how dynamic arrays grow, and the two techniques that turn most array interview problems into linear passes: prefix sums and two pointers.

Memory layout: why indexing is O(1)

An array is a contiguous block of memory. If the block starts at address base and each element occupies size bytes, then the element at index i lives at:

\[ \text{address}(i) = \text{base} + i \times \text{size} \]

No loop, no traversal — just arithmetic. That is why a[i] is \(O(1)\).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.95cm, minimum height=0.8cm, font=\small\bfseries}]
  \foreach \v [count=\i from 0] in {7,3,9,1,4} {
    \node[c, fill=blue!12] (n\i) at (\i*1.05,0) {\v};
    \node[font=\scriptsize\ttfamily] at (\i*1.05,-0.7) {\i};
  }
  \node[font=\scriptsize\ttfamily, anchor=west] at (-1.1,-0.7) {index};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.1,-1.2) {address(i) = base + i $\times$ size};
\end{tikzpicture}

The cost of that layout is inflexibility: inserting in the middle means shifting everything after it, and deleting leaves a hole. Arrays are fast to read and slow to change shape.

The operation table

Operation Complexity Why
Access a[i] \(O(1)\) address arithmetic
Update a[i] = x \(O(1)\) write one slot
Search (unsorted) \(O(n)\) must scan
Search (sorted) \(O(\log n)\) binary search (Chapter 8)
Insert at end \(O(1)\) amortized may resize
Insert/delete at front or middle \(O(n)\) shift the tail
Append (dynamic) \(O(1)\) amortized doubling

Memorize the two rows that surprise people: inserting at the front is \(O(n)\), and searching an unsorted array is \(O(n)\) no matter how clever you are.

Dynamic arrays: growth by doubling

Python’s list, Java’s ArrayList, and C++’s vector are dynamic arrays: a fixed block plus a length, which allocate a bigger block and copy when full. The strategy is to double:

class DynamicArray:
    def __init__(self):
        self.data = [None] * 2      # capacity
        self.size = 0               # useful elements
    def append(self, x):
        if self.size == len(self.data):
            self._grow()
        self.data[self.size] = x
        self.size += 1
    def _grow(self):
        bigger = [None] * (len(self.data) * 2)   # double
        for i in range(self.size):
            bigger[i] = self.data[i]             # copy O(n)
        self.data = bigger

Copying looks expensive, but because capacity doubles, the total copying across \(n\) appends is \(1 + 2 + 4 + \dots + n < 2n\) — amortized \(O(1)\) per append (Chapter 1). A doubling strategy is what makes append cheap without pre-allocating huge buffers.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.62cm, minimum height=0.62cm, font=\scriptsize}]
  \foreach \cap/\lab/\x in {2/{"size 2, full"}/0, 4/{"doubled to 4"}/2.6, 8/{"doubled to 8"}/6.2} {
    \foreach \i in {0,...,3} {
      \pgfmathparse{int(\i < \cap)}
      \ifnum\pgfmathresult=1
        \node[c, fill=green!25] at (\x+\i*0.68,0) {};
      \else
        \node[c, fill=gray!10] at (\x+\i*0.68,0) {};
      \fi
    }
    \node[font=\scriptsize, anchor=north] at (\x+1.0,-0.55) {\lab};
  }
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.5,-1.1) {grow by copying into a block twice as large};
\end{tikzpicture}

Technique: prefix sums

When a problem asks for many range sums, recomputing each one by scanning is \(O(n)\) per query. Precompute cumulative sums once:

\[ \text{prefix}[i] = a[0] + a[1] + \dots + a[i-1], \qquad \sum_{l}^{r-1} = \text{prefix}[r] - \text{prefix}[l] \]

Now every range sum is \(O(1)\) after an \(O(n)\) build.

def build_prefix(a):
    pre = [0] * (len(a) + 1)
    for i, x in enumerate(a):
        pre[i + 1] = pre[i] + x
    return pre

def range_sum(pre, l, r):        # sum of a[l:r]
    return pre[r] - pre[l]       # O(1)

a = [3, 1, 4, 1, 5, 9, 2]
pre = build_prefix(a)
print(range_sum(pre, 1, 4))      # a[1]+a[2]+a[3] = 1+4+1 = 6

The same idea generalizes to 2D prefix sums for submatrix queries. Prefix sums are the entry point to Fenwick and segment trees (Chapters 15–16), which support updates as well.

Technique: two pointers in place

Many array problems ask you to transform the array without extra space. Two pointers moving from opposite ends (or both from the left) do this in one pass.

Removing duplicates from a sorted array keeps a slow writer and a fast reader:

def remove_duplicates(nums):     # sorted, in place, returns new length
    if not nums:
        return 0
    write = 1                     # first element always kept
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write

Reversing in place swaps from both ends until they meet:

def reverse(a):
    l, r = 0, len(a) - 1
    while l < r:
        a[l], a[r] = a[r], a[l]
        l += 1
        r -= 1
    return a

Both are \(O(n)\) time and \(O(1)\) extra space. The pattern — one pointer to read, one to write, or two converging pointers — appears constantly in array problems (Chapter 27 goes deeper).

Searching in an array

If the array is unsorted, linear search is the best you can do: \(O(n)\).

def linear_search(a, target):
    for i, x in enumerate(a):
        if x == target:
            return i
    return -1

If it is sorted, binary search is \(O(\log n)\) — 20 steps for a million elements (Chapter 8):

def binary_search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Pitfalls

QQuestionSelf-check

Why is a[i] \(O(1)\) but insert(0, x) \(O(n)\)? When does a prefix-sum array beat recomputing sums?

ASolution

Indexing is address arithmetic on contiguous memory, independent of \(i\); inserting at the front shifts all existing elements right. Prefix sums win when you answer many range-sum queries: an \(O(n)\) build turns each query into \(O(1)\) instead of \(O(n)\).

Next: Linked Lists (DSA #3) — the structure that trades constant-time indexing for constant-time insertion.