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.
Question 102
Question 103
SurveyResults analyzes survey scores. scores is a nonnull ArrayList, possibly empty, with every value in [0,100]. The constructor keeps the supplied list reference.
public class SurveyResults {
private java.util.ArrayList scores
public SurveyResults(java.util.ArrayList initial){scores=initial;}
// Implement countAbove and trim.
}| Operation | Result |
|---|---|
| Initial scores | [85,42,90,42,73,100,15] |
| countAbove(50) | 4 |
| trim(40,90) | [85,42,90,42,73] |
| then trim(50,80) | [73] |
(a) Implement countAbove(int threshold), returning the number of scores strictly greater than threshold.
(b) Implement trim(int minAccept,int maxAccept), removing scores outside the inclusive range [minAccept,maxAccept], while preserving the relative order of all remaining values. Assume 0 <= minAccept <= maxAccept <= 100. Handle empty lists, removal of every element, and consecutive removals.
Main Solution
Answer Key
(a)
public int countAbove(int threshold){
int count=0
for(int value:scores)if(value>threshold)count++
return count
}
(b)
public void trim(int minAccept,int maxAccept){
for(int i=scores.size()-1;i>=0;i--)
if(scores.get(i)maxAccept)scores.remove(i)
}Answer images
Question 104
A grayscale image is represented as a rectangular 2D array of pixel values, where each entry is an integer in [0, 255]. The class ImageFilter provides operations on such images.
public class ImageFilter
{
/** The pixel grid. pixels[r][c] is the pixel at row r, column c.
* Each value is in [0, 255]. The grid has at least one row and
* one column, and every row has the same length. */
private int[][] pixels;
/** Constructs an ImageFilter around the given grid. */
public ImageFilter(int[][] p)
{
pixels = p;
}
/** Returns the maximum pixel value in the row range
* [startRow, endRow] (inclusive on both ends). Part (a) */
public int brightestIn(int startRow, int endRow)
{
/* part (a) */;
}
/** Applies an "invert then clip" filter to every pixel of pixels,
* modifying pixels in place. Part (b) */
public void invertAndClip(int floor)
{
/* part (b) */;
}
// Other methods are not shown.
}Part A
Write the method brightestIn. It returns the largest pixel value found anywhere in rows startRow through endRow of pixels, inclusive on both ends.
For example, suppose pixels is the following \(4 \times 5\) grid.
{ { 40, 12, 7, 30, 50 },
{ 15, 80, 20, 10, 5 },
{ 33, 33, 33, 33, 33 },
{ 99, 0, 60, 5, 42 } }
Then brightestIn(0, 1) returns 80, brightestIn(2, 2) returns 33, and brightestIn(0, 3) returns 99.
Assume 0 <= startRow <= endRow < pixels.length.
Part B
Write the method invertAndClip. It modifies pixels in place by applying the following to every pixel p:
- Compute the inverted value
255 − p. - If that inverted value is strictly less than
floor, replace the pixel withfloor(clip upward). - Otherwise, store the inverted value.
For example, if floor is 50 and a pixel has value 210, then \(255 - 210 = 45\), which is below 50, so the pixel becomes 50. If a pixel has value 100, then \(255 - 100 = 155\), which is not below 50, so the pixel becomes 155.
Using the \(4 \times 5\) example from Part A and calling invertAndClip(50), the resulting grid is:
{ { 215, 243, 248, 225, 205 },
{ 240, 175, 235, 245, 250 },
{ 222, 222, 222, 222, 222 },
{ 156, 255, 195, 250, 213 } }
(Every inverted value was already at least 50.) If instead the row { 240, 250, 252, 200, 220 } were present, calling invertAndClip(50) would produce { 50, 50, 50, 55, 50 } — four pixels clip up to the floor. Note that a pixel whose inverted value equals floor is not clipped. Assume 0 <= floor <= 255.
Main Solution
DETAILED SOLUTION — Question 46
Sample Solution
// Part (a)
public int brightestIn(int startRow, int endRow)
{
int best = pixels[startRow][0];
for (int r = startRow; r <= endRow; r++)
{
for (int c = 0; c < pixels[r].length; c++)
{
if (pixels[r][c] > best)
{
best = pixels[r][c];
}
}
}
return best;
}
// Part (b)
public void invertAndClip(int floor)
{
for (int r = 0; r < pixels.length; r++)
{
for (int c = 0; c < pixels[r].length; c++)
{
int inv = 255 - pixels[r][c];
if (inv < floor)
{
pixels[r][c] = floor;
}
else
{
pixels[r][c] = inv;
}
}
}
}
Rubric (9 pts): (a) 4 pts — iterates rows startRow..endRow inclusive, iterates all columns of each row, tracks a running max, returns the max. (b) 5 pts — visits every pixel in pixels, computes 255 − p, clips only when inverted is strictly less than floor, writes the result back in place to pixels[r][c], overall behavior matches spec (including the "equal to floor does NOT clip" edge case).
Teacher Explanation
255 − p and applying a strict less-than clip condition, storing results back in place.Education Coach Advice
Track the maximum across the inclusive row range. Initializing from an actual pixel is general and clear; for the stated [0,255] domain, zero or Integer.MIN_VALUE also works. Invert every pixel and store the larger of its inverted value and floor.
Traps
Visit all columns in every required row and update pixels in place for Part B. At equality, using <= rather than < assigns the same value and does not change the observable result. Do not reject a correct maximum initialized to zero for the nonnegative pixel domain.
Answer images
Question 105
A linguist is studying word usage in a corpus. Given an ArrayList<String> of the words that appear in a document (in order, with possible repetitions), the linguist wants the list of most common words in that document.
Write a static method mostFrequent that, given such a list, returns a new ArrayList<String> containing every word whose number of occurrences in words equals the maximum number of occurrences attained by any word. In the returned list:
- each qualifying word appears exactly once, even if it occurs many times in
words; - the qualifying words appear in the order of their first occurrence in
words.
Two words are considered the same only if they are equal as strings (case-sensitive). The parameter words must not be modified. If words is empty, return an empty list.
Method Signature
public static ArrayList<String> mostFrequent(ArrayList<String> words)
Examples
| Input words | Returned list | Explanation |
|---|---|---|
| ["to","be","or","not","to","be"] | ["to","be"] | Both appear twice; "to" occurs first, then "be". |
| ["red","blue","red","green","blue","red"] | ["red"] | Max count is 3 ("red"); "blue" has count 2. |
| ["a","b","c","d"] | ["a","b","c","d"] | All words tie at count 1; order is preserved. |
| ["Cat","cat","Cat"] | ["Cat"] | Case-sensitive: "Cat" has count 2, "cat" has count 1. |
| [] | [] | Empty input → empty output. |
Main Solution
Sample Solution
public static ArrayList<String> mostFrequent(ArrayList<String> words)
{
ArrayList<String> distinct = new ArrayList<String>();
ArrayList<Integer> counts = new ArrayList<Integer>();
for (int i = 0; i < words.size(); i++)
{
String w = words.get(i);
int idx = -1;
for (int j = 0; j < distinct.size(); j++)
{
if (distinct.get(j).equals(w))
idx = j;
}
if (idx == -1)
{
distinct.add(w);
counts.add(1);
}
else
{
counts.set(idx, counts.get(idx) + 1);
}
}
int max = 0;
for (int i = 0; i < counts.size(); i++)
{
if (counts.get(i) > max)
max = counts.get(i);
}
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < distinct.size(); i++)
{
if (counts.get(i) == max)
result.add(distinct.get(i));
}
return result;
}
Scoring. The two parallel lists distinct and counts (populated in input order) encode both the frequency table and the first-occurrence order for free. A single pass over counts finds the maximum; a final pass emits every entry whose count matches. The original words is never written to. Returning an empty list when words is empty falls out of the algorithm (the max stays 0 and the final loop produces nothing).
Teacher Explanation
Education Coach Advice
Traps
Answer images
Question 106
An image-processing routine applies a smoothing filter to a rectangular grid of integer pixel values. For each cell in the input grid, the smoothed grid contains the integer average (truncated toward zero, as with Java's int division) of that cell and its orthogonal neighbors — the cells directly above, below, to the left, and to the right, when they exist.
A corner cell therefore averages three values (itself and its two in-bounds orthogonal neighbors); an edge cell averages four; and an interior cell averages five. Diagonal neighbors are never included. The original grid must not be modified.
Write a static method gridSmooth that takes a rectangular 2-D array grid of non-negative integers (at least one row and one column; every row has the same length) and returns a new 2-D array of the same dimensions containing the smoothed values, as defined above.
Method Signature
public static int[][] gridSmooth(int[][] grid)
Example 1
Given the 3×4 grid on the left, the result is shown on the right. Each cell shows the full computation for reference.
| Input grid | Returned grid |
|---|---|
| |
For instance, the value at row 1, column 1 is \((6 + 8 + 2 + 3 + 1) / 5 = 20 / 5 = 4\) (itself, up, left, right, down — truncated). The value at row 0, column 0 is \((4 + 8 + 2) / 3 = 14 / 3 = 4\) (itself, right, down — truncated). The value at row 2, column 3 is \((9 + 5 + 7) / 3 = 21 / 3 = 7\).
Example 2
A 1×1 grid maps to itself: gridSmooth({{ 42 }}) returns {{ 42 }} (the sum is 42, divided by 1).
A 1×3 grid behaves as if every cell is on the top and bottom edge: gridSmooth({{ 3, 6, 9 }}) returns {{ 4, 6, 7 }}, since \((3+6)/2 = 4\), \((6+3+9)/3 = 6\), and \((9+6)/2 = 7\).
Main Solution
Sample Solution
public static int[][] gridSmooth(int[][] grid)
{
int rows = grid.length;
int cols = grid[0].length;
int[][] result = new int[rows][cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
long sum = grid[r][c];
int n = 1;
if (r > 0)
{
sum = sum + grid[r - 1][c];
n = n + 1;
}
if (r < rows - 1)
{
sum = sum + grid[r + 1][c];
n = n + 1;
}
if (c > 0)
{
sum = sum + grid[r][c - 1];
n = n + 1;
}
if (c < cols - 1)
{
sum = sum + grid[r][c + 1];
n = n + 1;
}
result[r][c] = (int) (sum / n);
}
}
return result;
}
Scoring. Allocate a fresh int[rows][cols] so the original grid is untouched. Four independent boundary guards (not a single nested condition) keep the logic clear and match the natural 3/4/5 neighbor counts at corners, edges, and interior cells. Integer division at the end gives Java's truncated-toward-zero semantics automatically for non-negative inputs.
Teacher Explanation
Education Coach Advice
Traps
Answer images
Question 107
This question involves analyzing daily high temperatures recorded over a season. The partial class TempLog below stores the temperatures in a double array.
public class TempLog
{
/** highs[k] is the recorded high temperature (in degrees Fahrenheit)
* for day k, where 0 <= k < highs.length. highs is never null
* and always contains at least one element. */
private double[] highs;
// Constructor not shown.
/** Returns the number of days whose high temperature was
* strictly greater than threshold, as described in part (a). */
public int daysHotterThan(double threshold)
{
/* to be implemented in part (a) */
}
/** Returns the length of the longest run of consecutive days
* whose high temperature was strictly greater than threshold,
* as described in part (b). */
public int longestHotStreak(double threshold)
{
/* to be implemented in part (b) */
}
}
Part (a)
Write the daysHotterThan method. The method returns the number of entries in highs that are strictly greater than threshold.
For example, if highs contains {72.5, 80.0, 68.1, 95.4, 80.0, 81.2}, then:
| Call | Returned value |
|---|---|
daysHotterThan(80.0) | 2 (only 95.4 and 81.2 are strictly greater) |
daysHotterThan(100.0) | 0 |
daysHotterThan(0.0) | 6 |
Complete method daysHotterThan below.
/** Returns the number of days whose high temperature was
* strictly greater than threshold, as described in part (a). */
public int daysHotterThan(double threshold)
Part (b)
Write the longestHotStreak method. The method returns the length of the longest run of consecutive days whose high temperature is strictly greater than threshold. If no day satisfies the condition, the method returns 0.
For example, if highs contains {60.0, 85.0, 90.0, 72.0, 95.0, 95.0, 95.0, 70.0}, then:
| Call | Returned value |
|---|---|
longestHotStreak(80.0) | 3 (days at indices 4, 5, 6) |
longestHotStreak(88.0) | 3 |
longestHotStreak(100.0) | 0 |
In writing longestHotStreak, you may assume daysHotterThan works as specified regardless of what you wrote in part (a). Complete method longestHotStreak below.
/** Returns the length of the longest run of consecutive days
* whose high temperature was strictly greater than threshold,
* as described in part (b). */
public int longestHotStreak(double threshold)
Main Solution
Sample Solution
Part (a) — Solution
public int daysHotterThan(double threshold)
{
int count = 0;
for (int i = 0; i < highs.length; i++)
{
if (highs[i] > threshold)
{
count++;
}
}
return count;
}
Scoring (4 pts): +1 correctly traverses highs (bounds correct); +1 uses strict > comparison; +1 increments a counter on match; +1 returns count after loop.
Part (b) — Solution
public int longestHotStreak(double threshold)
{
int longest = 0;
int current = 0;
for (int i = 0; i < highs.length; i++)
{
if (highs[i] > threshold)
{
current++;
if (current > longest)
{
longest = current;
}
}
else
{
current = 0;
}
}
return longest;
}
Scoring (5 pts): +1 correctly traverses highs; +1 increments a running streak on a hot day; +1 resets streak to 0 on a non-hot day; +1 updates maximum correctly; +1 returns the maximum and handles the all-cold case (returns 0). Common errors: (i) forgetting to reset current in the else; (ii) updating longest only at the end, which misses streaks that don't end on the last day (this solution avoids both).
Teacher Explanation
Education Coach Advice
Traps
Answer images
Question 108
Question 109
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.

