AP® Computer Science A Data Collections FRQ
Work through AP Computer Science A free-response questions on Data Collections, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Subtopic: 2D Arrays Clear filter
Question 32
Question 33
Question 34
Question 35
Question 36
A geographic survey team uses a 2D integer array to represent terrain elevation data. Each element stores the elevation in meters at that grid location. The team needs tools to analyze the border of the survey region and to detect notable peaks in the interior.
PART A
Write the method public int borderSum(int[][] grid) that returns the sum of all elements on the border of the grid (first row, last row, first column, last column). Each corner element is counted exactly once.
For example, if grid = {{5, 3, 8, 1}, {2, 7, 4, 9}, {6, 1, 3, 5}}, the border elements are 5, 3, 8, 1, 9, 5, 3, 1, 6, 2 and the sum is 43 (interior elements 7 and 4 are excluded).
public int borderSum(int[][] grid) {
}PART B
Write the method public int countPeaks(int[][] grid) that returns the number of interior cells (not on any edge) that are strictly greater than all four of their direct neighbors (up, down, left, right).
For example, if grid = {{1, 2, 1, 3}, {4, 8, 3, 1}, {1, 2, 9, 4}, {2, 1, 5, 2}}, the interior cells are at (1,1)=8, (1,2)=3, (2,1)=2, (2,2)=9. Cell (1,1)=8 is greater than all neighbors (2, 4, 3, 2) → peak. Cell (2,2)=9 is greater than all neighbors (3, 5, 2, 4) → peak. The method returns 2.
public int countPeaks(int[][] grid) {
}Main Solution
PART A — borderSum
The border of a 2D grid consists of: the first row, the last row, the first column, and the last column. Corner elements belong to two of these groups, so we must count them only once. A clean approach is to iterate over all four sides carefully, or to iterate over every cell and check whether it is on a border.
public int borderSum(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int sum = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
sum += grid[r][c];
}
}
}
return sum;
}Explanation:
- We loop over every cell
(r, c). - A cell is on the border if it is in the first row (
r == 0), the last row (r == rows-1), the first column (c == 0), or the last column (c == cols-1). - Corner cells satisfy two of these conditions but are added only once because the
ifcheck is evaluated once per cell. - Interior cells satisfy none of the conditions and are skipped.
Verification with the given example:
grid = {{5,3,8,1},{2,7,4,9},{6,1,3,5}}
Border cells: row 0 → 5+3+8+1=17; row 2 → 6+1+3+5=15; col 0 interior → 2; col 3 interior → 9.
Sum = 17 + 15 + 2 + 9 = 43 ✓
PART B — countPeaks
An interior cell is one that is not on any edge, i.e., row index is between 1 and rows-2 (inclusive) and column index is between 1 and cols-2 (inclusive). A peak is an interior cell strictly greater than all four direct neighbors.
public int countPeaks(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int count = 0;
for (int r = 1; r <= rows - 2; r++) {
for (int c = 1; c <= cols - 2; c++) {
int val = grid[r][c];
if (val > grid[r - 1][c] && // up
val > grid[r + 1][c] && // down
val > grid[r][c - 1] && // left
val > grid[r][c + 1]) { // right
count++;
}
}
}
return count;
}Explanation:
- We iterate only over interior cells: rows 1 through
rows-2, columns 1 throughcols-2. - For each interior cell we compare its value to its four direct (orthogonal) neighbors.
- If it is strictly greater than all four, it is a peak and we increment
count. - We return the final count.
Verification with the given example:
grid = {{1,2,1,3},{4,8,3,1},{1,2,9,4},{2,1,5,2}}
Interior cells (rows 1–2, cols 1–2):
(1,1)=8: neighbors up=2, down=2, left=4, right=3 → 8>2, 8>2, 8>4, 8>3 → peak ✓
(1,2)=3: neighbors up=1, down=9, left=8, right=1 → 3>9 is false → not a peak
(2,1)=2: neighbors up=8, down=1, left=1, right=9 → 2>8 is false → not a peak
(2,2)=9: neighbors up=3, down=5, left=2, right=4 → 9>3, 9>5, 9>2, 9>4 → peak ✓
Count = 2 ✓
Teacher Explanation
Part A tests the ability to iterate over a 2D array and identify border elements using index boundary conditions. The key insight is that a single if with four OR-connected conditions handles corners without double-counting. Part B tests nested loops over a restricted range (interior only) and multi-condition comparisons. Students must use strict inequality (>) and check all four neighbors. Common AP scoring criteria: correct loop bounds, correct border/interior identification, correct neighbor access without ArrayIndexOutOfBoundsException, and returning the correct value.
Education Coach Advice
For 2D array FRQs on the AP exam: (1) Always use grid.length for rows and grid[0].length for columns — never hard-code sizes. (2) For border problems, the single-loop approach with an if condition is cleaner and less error-prone than four separate loops. (3) For neighbor problems, write out the four neighbor accesses explicitly and double-check row vs. column order. (4) Trace through the provided example by hand before finalizing — the exam often gives you a concrete test case you can use to verify your logic.
Traps
Part A traps:
- Double-counting corners by summing each side in a separate loop without excluding corners from the column loops.
- Off-by-one errors: using
r < rows - 1instead ofr <= rows - 1(or equivalentlyr == rows - 1), missing the last row or column. - Hard-coding dimensions instead of using
grid.lengthandgrid[0].length.
Part B traps:
- Including edge cells in the loop (starting at row/col 0 or ending at row/col
rows-1/cols-1), which causesArrayIndexOutOfBoundsExceptionwhen accessing neighbors. - Using
>=instead of>(the problem says strictly greater). - Checking only some neighbors (e.g., forgetting the down or right neighbor).
- Confusing row and column indices when accessing neighbors (e.g., writing
grid[r-1][c-1]for the up neighbor instead ofgrid[r-1][c]).
Question 37
A smart building uses a grid of temperature sensors installed in the ceiling of a large warehouse floor. The sensor readings are stored in a 2D integer array where each element represents the temperature in degrees at that sensor's location. The facilities team needs analysis tools to monitor heating patterns and identify problem areas.
PART A
Write the method public int[] rowMaximums(int[][] temps) that returns a new 1D array where each element is the maximum temperature value found in the corresponding row of temps.
For example, if temps is {{72, 75, 68}, {80, 77, 82}, {69, 71, 70}}, the method returns {75, 82, 71}.
public int[] rowMaximums(int[][] temps) {
}PART B
Write the method public boolean hasHotspot(int[][] temps, int threshold) that returns true if there exists any \(2\times2\) sub-grid (four adjacent cells forming a square) where all four values are strictly greater than threshold. The method returns false otherwise.
For example, if temps is {{70, 85, 90}, {60, 88, 92}, {75, 80, 78}} and threshold is 80, the method returns true because the \(2\times2\) sub-grid at rows 0–1 and columns 1–2 contains {85, 90, 88, 92}, all greater than 80.
public boolean hasHotspot(int[][] temps, int threshold) {
}Main Solution
PART A — rowMaximums
The method must iterate over every row of the 2D array, find the maximum value in that row, and store it in a result array at the corresponding index.
public int[] rowMaximums(int[][] temps) {
int[] result = new int[temps.length];
for (int r = 0; r < temps.length; r++) {
int max = temps[r][0]; // start with first element of the row
for (int c = 1; c < temps[r].length; c++) {
if (temps[r][c] > max) {
max = temps[r][c];
}
}
result[r] = max;
}
return result;
}Trace with the given example:
- Row 0:
{72, 75, 68}→ max = 75 - Row 1:
{80, 77, 82}→ max = 82 - Row 2:
{69, 71, 70}→ max = 71
Returns {75, 82, 71} ✓
PART B — hasHotspot
The method must check every possible 2×2 sub-grid. A 2×2 sub-grid is defined by its top-left corner at (r, c); its four cells are (r,c), (r,c+1), (r+1,c), and (r+1,c+1). The top-left corner can range from row 0 to temps.length - 2 and column 0 to temps[r].length - 2.
public boolean hasHotspot(int[][] temps, int threshold) {
for (int r = 0; r < temps.length - 1; r++) {
for (int c = 0; c < temps[r].length - 1; c++) {
if (temps[r][c] > threshold &&
temps[r][c+1] > threshold &&
temps[r+1][c] > threshold &&
temps[r+1][c+1] > threshold) {
return true;
}
}
}
return false;
}Trace with the given example (temps = {{70,85,90},{60,88,92},{75,80,78}}, threshold = 80):
- Sub-grid at (0,0): 70, 85, 60, 88 — 70 is not > 80 → skip
- Sub-grid at (0,1): 85, 90, 88, 92 — all > 80 → return
true✓
Teacher Explanation
Part A tests the ability to traverse a 2D array row by row and apply a running-maximum algorithm, then store results in a 1D array. Key pitfalls: initializing max to Integer.MIN_VALUE or 0 instead of the first element of the row (both work, but using the first element is cleaner and avoids edge cases with all-negative temperatures).
Part B tests nested-loop boundary control. The outer loop must stop at temps.length - 1 (not temps.length) and the inner loop at temps[r].length - 1 to avoid an ArrayIndexOutOfBoundsException. The condition must use strict greater-than (>), not >=, as specified by "strictly greater than."
Education Coach Advice
AP Exam Strategy:
- For 2D array traversal problems, always write out the loop bounds explicitly and double-check them against the array dimensions before moving on.
- For "find the maximum" problems, initialize your running max to the first element of the collection, not to 0 or a magic number.
- For sub-grid problems, remember the top-left corner of an \(n \times n\) sub-grid can only go up to
length - nin each dimension. - Trace through the provided example by hand after writing your code — the AP graders reward correct logic even if syntax is slightly off, but a wrong trace means wrong logic.
- Use
return trueas soon as you find a hotspot (early exit); onlyreturn falseafter all sub-grids have been checked.
Traps
Common errors and traps:
- Off-by-one in Part B: Using
r < temps.lengthinstead ofr < temps.length - 1causes anArrayIndexOutOfBoundsExceptionwhen accessingtemps[r+1]. - Wrong comparison operator in Part B: Using
>=instead of>violates the "strictly greater than" requirement and will fail test cases where a cell equals the threshold exactly. - Initializing max to 0 in Part A: If all temperatures in a row are negative, initializing
max = 0would return an incorrect result. Always initialize to the first element of the row or toInteger.MIN_VALUE. - Returning the wrong array length in Part A: The result array must have length
temps.length(number of rows), nottemps[0].length(number of columns).
Question 38
Question 39
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

