FRQ Type 4: 2D Array

Practice these in the app

The fourth free-response question gives you a class that keeps a two-dimensional array, often of objects of a provided class with a few getters, and asks for a method that reads it: the total of one row, a count of the rows or columns that pass a test, or a value worked out from a cell's neighbors.
It is always the fourth of the exam's four free-response questions: one method that reads the array, worth 6 of their 25 points.

Rows, columns, and the size of the grid

The examples on this page use a vineyard planted in rows. Each spot holds a Vine with two getters, and the vineyard keeps them in a 2D array:
public class Vine
{
    /** Returns the kind of grape on this vine */
    public String getGrape()
    { /* implementation not shown */ }

    /** Returns the number of grape clusters on this vine, always >= 0 */
    public int getClusters()
    { /* implementation not shown */ }
}

public class Vineyard
{
    /** vines[r][c] is the vine in row r, column c */
    private Vine[][] vines;

    /* methods to be written */
}
The first index is the row and the second is the column. The number of rows is vines.length, and the number of columns is vines[0].length, the length of the first row. The examples use a vineyard of 3 rows and 4 columns:
Column 0Column 1Column 2Column 3
Row 0Merlot, 5Merlot, 8Syrah, 2Merlot, 6
Row 1Syrah, 7Syrah, 3Syrah, 9Merlot, 4
Row 2Merlot, 1Syrah, 6Merlot, 5Merlot, 2
A grid with as many rows as columns hides the most common mistake, which is bounding the columns by vines.length. On this grid that loop stops after column 2, and in a grid with more rows than columns it throws an ArrayIndexOutOfBoundsException on the first row. Check your loops against a grid that isn't square.

One row or one column

A single row is an ordinary 1D array, so an enhanced for loop can walk it:
public int rowClusters(int row)
{
    int total = 0;
    for (Vine v : vines[row])
    {
        total += v.getClusters();
    }
    return total;
}
rowClusters(1) returns 7 + 3 + 9 + 4 = 23. A column is not stored as an array of its own, so walking one needs the row index to change while the column stays fixed: vines[r][col] for r from 0 while r < vines.length. Column 2 totals 16. The 2026 guide took the algorithm point from a response that summed a column when the question asked for a row.

A rule decided after the loop

Many questions ask whether every cell in a row or column passes a test. Start a boolean at true, set it to false when a cell fails, and read it only after the loop:
public boolean allAtLeast(int col, int k)
{
    boolean all = true;
    for (int r = 0; r < vines.length; r++)
    {
        if (vines[r][col].getClusters() < k)
        {
            all = false;
        }
    }
    return all;
}
allAtLeast(0, 2) is false, because of the vine with 1 cluster in row 2, and allAtLeast(1, 3) is true. Writing else all = true;, or returning true in an else inside the loop, decides from one cell instead of all of them. Returning false at the first failing cell is correct when nothing else is left to compute, but when the method also needs a total of the row, an early return skips part of it. In 2026 that cost the algorithm point for the returned value.
Some rules compare cells with each other along a row or a column, such as whether every cell in a row matches the one next to it. Then the loop stops one cell early, c < vines[row].length - 1, and compares vines[row][c] with vines[row][c + 1], or starts at 1 and looks back. A row of 4 cells has 3 such pairs. In 2022 a bounds error on the first or last pair cost a point, and in 2026 a response that counted matching pairs had to compare the count with the number of pairs, not the number of cells.

Every row or every column

When the question asks how many rows or columns pass a test, the test above goes inside an outer loop. Its boolean must start over for each row or column, so it is declared inside the outer loop:
public int columnsWith(String grape)
{
    int count = 0;
    for (int c = 0; c < vines[0].length; c++)
    {
        boolean found = false;
        for (int r = 0; r < vines.length; r++)
        {
            if (vines[r][c].getGrape().equals(grape))
            {
                found = true;
            }
        }
        if (found)
        {
            count++;
        }
    }
    return count;
}
columnsWith("Syrah") returns 3, since column 3 has none. Declared once before the outer loop, found would stay true after the first column with a Syrah vine, and every later column would count. Because the outer loop runs over columns and the inner one over rows, this walks the grid in column-major order, one column at a time. The 2022 question scored that order directly. Compare the grape names with equals; in 2026, == on two cells' colors lost the point for the comparison.

Neighbors and bounds

A cell's neighbors are the cells above, below, left, and right of it, and cells on an edge have fewer of them. Each neighbor gets its own guard, tested before the neighbor is read. Because && stops at the first false, the cell is never read when the guard fails:
public boolean matchesNeighbor(int r, int c)
{
    String g = vines[r][c].getGrape();
    return (r > 0 && vines[r - 1][c].getGrape().equals(g))
        || (r < vines.length - 1 && vines[r + 1][c].getGrape().equals(g))
        || (c > 0 && vines[r][c - 1].getGrape().equals(g))
        || (c < vines[0].length - 1 && vines[r][c + 1].getGrape().equals(g));
}
The Merlot vine in row 0, column 0 has a Merlot neighbor to its right, so matchesNeighbor(0, 0) is true. The Merlot vine in row 2, column 0 has a Syrah vine above it and to its right, and no neighbor below or to its left, so it's false. Leaving out a guard throws an ArrayIndexOutOfBoundsException on the edge. Read the question for which neighbors count: 2016 used the cells above and to the left, and 2024 the cells below and to the right.

Blocks and ranges

A question that names a block of the grid by its corners includes both corners. Both loops use <=:
public int clustersIn(int top, int left, int bottom, int right)
{
    int total = 0;
    for (int r = top; r <= bottom; r++)
    {
        for (int c = left; c <= right; c++)
        {
            total += vines[r][c].getClusters();
        }
    }
    return total;
}
The block from row 0, column 1 to row 1, column 2 totals 8 + 2 + 3 + 9 = 22. An average over a block divides by the number of cells in it, as a double.

The best cell

Finding the cell with the greatest or least value keeps the best cell seen so far and replaces it when a better one comes along. When the question adds a condition, only the cells that meet it are compared:
/** Returns the vine of the given grape with the most clusters,
 *  or null if no vine has that grape */
public Vine mostClusters(String grape)
{
    Vine best = null;
    for (int r = 0; r < vines.length; r++)
    {
        for (int c = 0; c < vines[0].length; c++)
        {
            Vine v = vines[r][c];
            if (v.getGrape().equals(grape)
                && (best == null || v.getClusters() > best.getClusters()))
            {
                best = v;
            }
        }
    }
    return best;
}
mostClusters("Syrah") returns the vine in row 1, column 2, with 9 clusters, and mostClusters("Merlot") the one in row 0, column 1, with 8. A grape that isn't planted gives null. Starting best at null lets the first matching vine become the best, wherever it is. Starting it at vines[0][0] works here only because a Syrah vine has more than the 5 clusters of that Merlot vine; if the best Syrah had 4, the method would return the Merlot. The first cell is a safe start only when every cell counts.
Ties depend on the order of the loops. Row by row with >, the first of the tied cells in reading order stays the best: the smaller row index, and in the same row the smaller column index. With >= the last one wins, and a column-major loop meets the tied cells in a different order. When the question names which of the tied cells to return, check that your loops reach that one first.
When the answer is a place rather than a cell, keep the row and the column in two int variables, updated together. When it is a whole row, such as the row whose vines hold the most clusters, the row's total starts over inside the outer loop, like found in columnsWith, and is compared with the best total after the inner loop ends: the rows total 21, 23, and 14, so the answer is row 1.

Leave the grid unchanged

Since 2026 the method only reads the grid. Assigning to a cell, or changing an object in one, falls under "Persistent data is modified" and costs an algorithm point. Older questions built the grid in a constructor, filled it with random values, or emptied cells, and those parts needed new, Math.random, and careful indexes; none of that appears in the current version.

Scoring notes

  • In 2026 the six points were: accessing every element of the target row with no bounds error; calling a getter on an element; comparing two cells' colors; starting a total and adding to it in a loop; the algorithm point for deciding whether every space in the row had the same color; and the algorithm point for computing and returning the row's value.
  • The two algorithm points are separate. A wrong same-color test cost the first of them and left the second, so a response could earn the point for the returned total with a wrong test.
  • The narrower points forgive a lot. In 2026 an element accessed incorrectly still earned the points for the getter call, the comparison, and the total; rows and columns swapped still earned the comparison and the total; and a bounds error still earned the getter call.
  • An early return that skipped cells, a sum over a column instead of the row, and printing the answer each cost an algorithm point. A total never started cost the point for the total.
  • Through 2025 a question had two or three parts, one of which often built the grid, and penalties of 1 point each for errors such as printing or changing data. Since 2026 those errors cost an algorithm point.
  • The general rules ignore length written with or without parentheses, a local variable used without being declared, and a missing brace where the indentation shows the structure.

Common traps

  • The column loop bounded by grid.length, the number of rows.
  • Row and column indexes swapped, as in grid[c][r].
  • A boolean or count declared before the outer loop, so it never starts over for the next row or column.
  • A decision made from the first cell: an else that sets the flag back or returns inside the loop.
  • A neighbor read without its guard, or a guard tested after the read instead of before it.
  • == on Strings from two cells.
  • A block or range that leaves out its last row or column because the loop uses < where the question includes the end.
  • An average computed with int division.
  • A best cell started at grid[0][0] when the first cell may not meet the question's condition.
  • >= where the question wants the first of the tied cells.
  • Assigning to a cell of the grid.

A full question

Every pair has a box on its left or on top. So the method visits every box and pairs it only with the box to its right and the box below it, each when that box exists:
public int countBusyPairs(int k)
{
    int count = 0;
    for (int r = 0; r < boxes.length; r++)
    {
        for (int c = 0; c < boxes[0].length; c++)
        {
            int mine = boxes[r][c].getLetters();
            if (c < boxes[0].length - 1 && mine + boxes[r][c + 1].getLetters() >= k)
            {
                count++;
            }
            if (r < boxes.length - 1 && mine + boxes[r + 1][c].getLetters() >= k)
            {
                count++;
            }
        }
    }
    return count;
}
Checking all four neighbors of every box would find each pair twice, once from each of its boxes, and return 12 for the example. The two guards keep the right-hand column from looking past the edge and the bottom row from looking below the wall; without them the method throws an ArrayIndexOutOfBoundsException. "At least" makes the test >=: with >, the three pairs that hold exactly 10 letters drop out and the method returns 3.
A scoring guide for this question, written in the style of the 2026 guidelines, could read:
PointEarned forNotes
1Accesses every element of boxes (no bounds errors in the traversal)Not earned if the column loop is bounded by the number of rows
2Calls getLetters on an element of boxesEarned even if an element is accessed incorrectly
3Adds the letters of two boxes next to each other and compares the sum with kEarned even with the wrong strictness
4Starts a count and adds to it inside a conditional, in the context of a loopEarned even if the pairs counted are wrong
5 (algorithm)Considers every pair of boxes next to each other exactly once, guarded against a bounds errorNot earned for counting a pair twice, for missing the pairs one above the other, or for an unguarded neighbor
6 (algorithm)Returns the number of busy pairs, with boxes unchangedNot earned for an early return, for printing the count, or for changing a box
Here is the method in a program with the example's wall. Press Run, then change the numbers, try other values of k, or change >= to >.
public class Main
{
    public static void main(String[] args)
    {
        int[][] letters = {
            {2, 8, 1, 5},
            {6, 2, 7, 0},
            {4, 5, 9, 3}
        };
        PostBox[][] wall = new PostBox[letters.length][letters[0].length];
        for (int r = 0; r < letters.length; r++)
        {
            for (int c = 0; c < letters[0].length; c++)
            {
                wall[r][c] = new PostBox(letters[r][c]);
            }
        }

        PostOffice office = new PostOffice(wall);
        System.out.println("Pairs with at least 10 letters: " + office.countBusyPairs(10));
        System.out.println("Pairs with at least 15 letters: " + office.countBusyPairs(15));
    }
}
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.

Released exam index

Every released question built on a 2D array, 2011 to 2026. Before 2026 most had a part that built the array or changed its cells, which the current version no longer asks for.
ExamClassKey features
2011 Q4RouteCipherFill a 2D array of one-letter Strings row by row from a message, padding with "A"; encrypt a message block by block
2012 Q4GrayImageCount the white pixels; subtract the value two rows down and two columns right, inside the bounds
2013 Q4SkyViewFill rows from a 1D array in alternating directions; the average over an inclusive block
2014 Q3SeatingChart, StudentFill seats column by column from a list; remove students over an absence limit and count them
2015 Q1DiverseArraySum a 1D array; the row sums as an array; true if every row sum differs
2016 Q3Crossword, SquareA cell gets a label if it is white and has a black square or the edge above or to its left; number the labeled cells in order
2017 Q4SuccessorArray, PositionThe position of a value or null; a 2D array of the positions of each value's successor
2018 Q4ArrayTesterCopy a column into a 1D array; a Latin square checked with provided helpers
2019 Q4LightBoardFill a boolean grid with lights on at random 40% of the time; decide a light from the count of lights on in its column
2021 Q4ArrayResizerTrue if a row has no zeros; copy the rows with no zeros into a new, smaller array
2022 Q4DataFill with random values meeting three rules; count the columns in increasing order, walking each column
2023 Q4BoxOfCandy, CandyBring a candy up a column into the empty first row; find and remove the first candy of a flavor, searching rows from the bottom
2024 Q4GridPath, LocationThe smaller of the neighbors below and to the right that exist; the sum along the path to the bottom-right cell
2025 Q4SumOrSameGameFill with random values from 1 to 9; clear a cell and a partner in the same row or a later one, not the cell itself, whose values are equal or sum to 10
2026 Q4GameBoard, SpaceThe points of one row, doubled if every space in the row has the same color