๐ WAYPOINT LESSON
Grid search and the null contract
โญ beginnerโณ 12 min read๐ Lesson 59 of 256
Coordinate search with early return, null contracts, not-found testing.
Searching a grid โ find a value and report where it lives:
// returns {row, col} or null if absent
public static int[] find(int[][] g, int target) {
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[0].length; c++) {
if (g[r][c] == target) {
return new int[] {r, c};
}
}
}
return null;
}
Three habits from this snippet that recur on FRQ 4:
- Early return the moment the target is found โ no flag needed.
- Return null (or a sentinel like -1) when not found; the contract
must say which.
nullmeans "no object here" โ calling a method on it throwsNullPointerException. - Test the not-found path on purpose. Un-tested contracts rot.
Grid size conventions: many AP grids are square-ish or have
different row/column counts on purpose โ {{1,2,3},{4,5}} is legal
(a "ragged" shape, though the exam's grids are usually rectangular).
Never assume rows and columns are interchangeable: g[r][c] and
g[c][r] are different cells, and one of them may not exist.
โก Now practice
Ready to Code2D array repsRow sums, transpose, path counting, coordinate search, accumulator debugging.
5 challenges ยท ยท ~55 min