format_list_numbered

Arrays &
Prefix Techniques

Precompute cumulative information to answer range queries efficiently.

What This Category Is Really About

01. Order

Elements have fixed positions. Queries on [L, R] always ask about the same subsequence. This predictability enables preprocessing.

02. Accumulation

Operations compose: sums add, products multiply, XOR chains. Build cumulative results once, answer any range query without recomputation.

03. Locality

Range queries depend only on two boundary values. Middle elements don't matter. This locality enables O(1) queries.

lightbulb

"Many DSA problems start here. Once you recognize repeated questions about fixed ranges or cumulative state tracking, prefix techniques become your first instinct."

Mental Model & Invariant

Prefix thinking: compute once, query many times.

Build an auxiliary structure storing cumulative results from start to each position. Any range query becomes a simple operation on two precomputed values.

The Master Invariant
prefix[i] = op(arr[0]...arr[i])

This must hold true at every index during construction.

select_all

Range Queries

Any [L, R] answered by combining two prefix values, not iterating.

settings_input_component

Operation Constraint

Must be reversible or associative to isolate [L, R].

bolt

Complexity

O(n) preprocessing, O(1) per query.

When to Think "Array + Prefix"

wifi_tetheringStrong Signals

1.

Multiple queries on fixed array

2.

Sum, product, or count queries

3.

Need faster than O(n) per query

4.

Cumulative or running totals

lock_openConstraint Signals

1.

Static or infrequent updates

2.

Reversible or associative operation

3.

Query count justifies preprocessing

Prefix Techniques You Must Master

Simple Traversal + State

Track running state as you iterate; answer queries about state at each position.

// Invariant
state[i] = f(state[i-1], arr[i])

Prefix Sum

Answer range sum queries in O(1) after O(n) preprocessing.

// Invariant
prefix[i] = arr[0] + ... + arr[i]

Prefix Sum + HashMap

Find subarrays with specific cumulative properties without nested loops.

// Invariant
If prefix[j] - prefix[i] = target, then sum(i+1, j) = target.

Prefix / Suffix Products

Compute products or results that depend on elements before and after a position.

// Invariant
prefix[i] = prod(0, i); suffix[i] = prod(i, n-1)

Difference Array

Apply multiple range updates efficiently (diff[L]+=v, diff[R+1]-=v), then prefix sum recoveries.

// Invariant
diff[i] = arr[i] - arr[i-1]

Cumulative Frequency

Track how many elements satisfy a condition up to each position.

// Invariant
freq[i] = count(arr[0..i] meets cond)

How to Learn These Techniques

1

Understand Brute Force

Write how you'd answer a query by iterating the range. Identify what computation repeats.

2

Identify What Accumulates

Determine which operation can be precomputed. Verify it's reversible or associative.

3

State the Invariant

Write exactly what each prefix position stores. This must be true at every step.

4

Verify on a Small Example

Trace your formula on paper with explicit indices before coding.

5

State complexity trade-offs

O(n) preprocessing vs O(1) query. Trading O(n) space for speed.

Canonical Problem List

Common Mistakes

warning

Off-by-one errors in range queries

The Problem

Confusion about inclusive vs. exclusive bounds; prefix array indexing mismatch.

The Fix

Trace your formula on paper with explicit indices before coding.

warning

Prefix on non-reversible operations

The Problem

Query formula fails; cannot isolate range [L, R] from full prefix results.

The Fix

Verify operation is reversible (subtraction) or associative before applying prefix.

warning

Forgetting to handle the L=0 case

The Problem

Query with L=0 accesses prefix[-1], causing index out of bounds.

The Fix

Add a dummy prefix[0] = 0 or handle L=0 as a special case explicitly.

warning

Rebuilding prefix array on every update

The Problem

Each update takes O(n); total time becomes O(n × updates).

The Fix

Use difference array for batch updates or Segment Trees for frequent updates.

Interview Guidance

Cheat Sheet

What they test

  • Preprocessing trade-offs: space vs speed
  • Thinking in invariants before coding
  • Verifying edge cases analytically

Clarity Signals

Explaining a prefix approach demonstrates thinking in invariants, not just code. Articulate what each position stores and why the formula works to signal disciplined thinking.

Verbal Template

STEP 1

"Double down on constraints. Mention brute force is O(n) per query."

STEP 2

"Clearly state: 'My invariant is prefix[i] = cumulative op.'"

STEP 3

"Trace a 3-element example out loud with indices."

STEP 4

"Confirm complexity is O(N) prep and O(1) query."

When You've Mastered It

check_circle

Pattern recognition is immediate

check_circle

Invariant is written before code

check_circle

Edge cases (L=0) verified by hand

check_circle

Operation reversibility verified

check_circle

Choosing right technique (diff array vs tree)

check_circle

Reasoning from first principles

What This Unlocks Next

view_sidebar

Sliding Window

Extends prefix thinking to dynamic windows that expand and contract.

troubleshoot

Binary Search

Answers 'where is the boundary?' while prefix answers 'what's the state?'

account_tree

Segment Trees

Generalizes prefix sum to O(log N) updates for dynamic arrays.

compare_arrows

Two Pointers

Uses movement instead of prep to avoid redundant iteration.

"The pattern is always the same: identify what accumulates, store it, answer efficiently."