synopsis · Linear patterns · chapter 10
Arrays & Strings
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
An array is one block of equal-sized slots:
arr[i]lives at base + i × size, so reading any index is O(1). - cost
Index O(1) · ArrayList append O(1) amortized · insert/delete in the middle O(n) · search unsorted O(n).
- use it when
Subarray max → Kadane. Except-self → prefix/suffix. Letters →
int[26]. More than n/2 → vote. Values 1..n → index v − 1. - template
Kadane:
cur = Math.max(x, cur + x); best = Math.max(best, cur);— start both atnums[0]. - template
Next permutation: pivot = first dip from the right → swap with the rightmost bigger value → reverse the suffix.
- trap
s += cin a loop is O(n²): every += copies the whole string. Build withStringBuilder, calltoString()once. - trap
list.remove(7)on aList<Integer>removes index 7, not the value 7. Writeremove(Integer.valueOf(7)). - trap
Rotate by k:
k %= nfirst. Circular max: all-negative input must return the Kadane max, not total − min. - pro tip
Before a nested loop, ask: one pass + a few running variables? Running min, best-ending-here, a vote counter.
- pro tip
O(1) space asked? Reverse in place, use the output array as scratch, or let index v − 1 remember value v.
Shaky on a card? Open the chapter or flip its recall cards.