~/problems
Problems
Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.
Prefix sums and difference arrays
O(1) range sums (1D and 2D); O(1) range updates with difference arrays.
Notes
Recognise it when: you need many range-sum queries on a static array, subarray sums equal to k (with a hash map), or many range updates followed by one read.
P = [0] * (n + 1)
for i, x in enumerate(a): P[i + 1] = P[i] + x
sum(a[l:r]) == P[r] - P[l]
# 2D: S[r+1][c+1] = g[r][c] + S[r][c+1] + S[r+1][c] - S[r][c]
# rect (r1, c1)..(r2, c2) inclusive:
S[r2+1][c2+1] - S[r1][c2+1] - S[r2+1][c1] + S[r1][c1]
# Difference array: add v to a[l..r]
D[l] += v; D[r + 1] -= v # then prefix-sum D once
Gotchas: stay consistent with 1-indexed prefix arrays and inclusive vs exclusive bounds. Write the 2D formula from a picture.
8 problems
Interview roadmap
Arrays & hashing Counting, lookups, sorting with keys, prefix sums.
Prefix sums and difference arrays guide
- Basics: range sums with a prefix array basics py · c++ · java easy
- Uphill metres between checkpoints py · c++ · java easy
- Range Sum Query 2D Immutable py · c++ · java easy
- Product of Array Except Self py · c++ · java medium
- Seat totals from range bookings py · c++ · java medium
- Count subarrays with a target sum (any sign) py · c++ · java medium
- Count of Stable Subarrays CitadelScale AI py · c++ · java medium
- Max Levels from Each Index Uber py · c++ · java medium