AP® Computer Science A FRQ Practice: Free-Response Questions with Solutions
Work through AP Computer Science A free-response questions unit by unit, 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 272
Question 273
Question 274
Question 275
Question 276
Question 277
Question 278
An online community platform stores user posts as strings in an ArrayList. The moderation team needs tools to clean up duplicate content and identify trending topics. You are writing two analysis methods for the MessageBoard class.
PART A
Write the method public ArrayList<String> removeDuplicates(ArrayList<String> posts) that returns a new ArrayList containing only the first occurrence of each unique string, in original order.
For example, if posts is ["hello", "world", "hello", "java", "world", "hello"], the method returns ["hello", "world", "java"].
public ArrayList<String> removeDuplicates(ArrayList<String> posts) {PART B
Write the method public String mostFrequent(ArrayList<String> posts) that returns the string appearing most often. If there is a tie, return the one that appears first in the list.
For example, if posts is ["cat", "dog", "cat", "bird", "dog", "cat"], the method returns "cat" (appears 3 times).
public String mostFrequent(ArrayList<String> posts) {Main Solution
PART A — removeDuplicates
The goal is to iterate through posts and add each string to a new ArrayList only if it has not already been added. This preserves the first occurrence and maintains original order.
public ArrayList<String> removeDuplicates(ArrayList<String> posts) {
ArrayList<String> result = new ArrayList<String>();
for (String post : posts) {
if (!result.contains(post)) {
result.add(post);
}
}
return result;
}Trace with example: posts = ["hello", "world", "hello", "java", "world", "hello"]
- "hello" → not in result → add → result = ["hello"]
- "world" → not in result → add → result = ["hello", "world"]
- "hello" → already in result → skip
- "java" → not in result → add → result = ["hello", "world", "java"]
- "world" → already in result → skip
- "hello" → already in result → skip
Returns ["hello", "world", "java"] ✓
PART B — mostFrequent
The goal is to find the string with the highest frequency. In case of a tie, the one that appears first in the list wins. We iterate through each unique string (using the result of removeDuplicates or a manual check), count its occurrences, and track the maximum.
public String mostFrequent(ArrayList<String> posts) {
if (posts == null || posts.size() == 0) {
return null;
}
String mostFreq = posts.get(0);
int maxCount = 0;
// Count occurrences of each string in original order
ArrayList<String> seen = new ArrayList<String>();
for (String post : posts) {
if (!seen.contains(post)) {
seen.add(post);
int count = 0;
for (String s : posts) {
if (s.equals(post)) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
mostFreq = post;
}
}
}
return mostFreq;
}Trace with example: posts = ["cat", "dog", "cat", "bird", "dog", "cat"]
- "cat": count = 3 → maxCount = 3, mostFreq = "cat"
- "dog": count = 2 → 2 < 3, no update
- "bird": count = 1 → 1 < 3, no update
Returns "cat" ✓
Tie-breaking note: Because we iterate through posts in order and only update mostFreq when count > maxCount (strict greater-than), the first string encountered with the highest count is retained, satisfying the tie-breaking requirement.
Teacher Explanation
Part A tests the student's ability to build a new collection by filtering duplicates using ArrayList.contains() and a for-each loop. Key scoring points: (1) creates and returns a new ArrayList, (2) uses contains or equivalent logic to check for prior occurrence, (3) adds only on first occurrence, (4) preserves original order.
Part B tests nested iteration to count frequencies and track a running maximum. Key scoring points: (1) correctly counts occurrences of each string, (2) uses strict > (not >=) to preserve first-occurrence tie-breaking, (3) returns the correct string, (4) handles the full list without skipping elements.
Education Coach Advice
AP Exam Strategy:
- For Part A, always create a new ArrayList and return it — never modify the parameter directly unless the prompt explicitly says to.
- For Part B, write out a small trace (like the example given) to verify your tie-breaking logic before finalizing your answer.
- Use
.equals()for all String comparisons in Java — never==. - Read the tie-breaking rule carefully: "first in the list" means use strict
>, not>=. - If you use a helper method (like calling
removeDuplicatesinsidemostFrequent), make sure it is correctly implemented — errors propagate.
Traps
Part A traps:
- Modifying the original
postslist instead of creating a new one — loses points for not returning a new ArrayList. - Using
==instead of.equals()for String comparison — will fail for non-interned strings. - Forgetting to return the result list.
Part B traps:
- Using
>=instead of>when updating the maximum — this would return the last string with the highest count instead of the first, violating the tie-breaking rule. - Counting each string multiple times (not tracking which strings have already been counted) — leads to redundant work but may still produce correct output; however, it risks off-by-one logic errors.
- Returning
nullor an empty string when the list is non-empty.
Question 279
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 280
A neighborhood book club meets monthly to discuss and rate books. Members rate each book on a scale of 1 to 10, and the club maintains two parallel ArrayLists: one for book titles and one for their average ratings. The BookClub class provides methods to help members select their next read.
PART A
Write the method public ArrayList<String> getTopRated(ArrayList<String> titles, ArrayList<Integer> ratings, int threshold) that returns a new ArrayList containing only the titles whose corresponding rating is greater than or equal to threshold, preserving the original order.
For example, if titles is ["Dune", "1984", "Cosmos", "Beloved"] and ratings is [9, 7, 8, 6] with threshold 8, the method returns ["Dune", "Cosmos"].
public ArrayList<String> getTopRated(ArrayList<String> titles, ArrayList<Integer>
ratings, int threshold) {PART B
Write the method public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) that removes and returns the title with the highest rating. If there is a tie, remove and return the one appearing earliest in the list. Both the titles and ratings lists should have the corresponding element removed.
For example, if titles is ["Dune", "1984", "Cosmos"] and ratings is [9, 7, 9], the method returns "Dune" (first with highest rating 9) and both lists are reduced to ["1984", "Cosmos"] and [7, 9].
public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) {Main Solution
PART A — getTopRated
Algorithm: Create a new ArrayList<String>. Iterate through every index of titles. At each index, compare the corresponding element of ratings to threshold. If the rating is greater than or equal to threshold, add the title at that index to the result list. Return the result list.
public ArrayList<String> getTopRated(ArrayList<String> titles,
ArrayList<Integer> ratings, int threshold) {
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < titles.size(); i++) {
if (ratings.get(i) >= threshold) {
result.add(titles.get(i));
}
}
return result;
}Trace with example: titles = ["Dune", "1984", "Cosmos", "Beloved"], ratings = [9, 7, 8, 6], threshold = 8.
- i=0: rating 9 ≥ 8 → add "Dune"
- i=1: rating 7 ≥ 8? No
- i=2: rating 8 ≥ 8 → add "Cosmos"
- i=3: rating 6 ≥ 8? No
Returns ["Dune", "Cosmos"] ✓
PART B — recommend
Algorithm: Track the index of the maximum rating seen so far. Initialize maxIndex = 0. Iterate from index 1 through the end of ratings. If the current rating is strictly greater than the rating at maxIndex, update maxIndex. (Using strictly greater than ensures ties are broken by earliest occurrence.) After the loop, save the title at maxIndex, then remove the element at maxIndex from both titles and ratings. Return the saved title.
public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) {
int maxIndex = 0;
for (int i = 1; i < ratings.size(); i++) {
if (ratings.get(i) > ratings.get(maxIndex)) {
maxIndex = i;
}
}
String topTitle = titles.get(maxIndex);
titles.remove(maxIndex);
ratings.remove(maxIndex);
return topTitle;
}Trace with example: titles = ["Dune", "1984", "Cosmos"], ratings = [9, 7, 9].
- maxIndex starts at 0 (rating 9)
- i=1: rating 7 > 9? No
- i=2: rating 9 > 9? No (tie — maxIndex stays 0)
topTitle = "Dune". Remove index 0 from both lists → titles = ["1984", "Cosmos"], ratings = [7, 9]. Returns "Dune" ✓
Teacher Explanation
Part A tests the ability to traverse two parallel ArrayLists simultaneously using a standard index-based for loop and selectively populate a new list — a core AP CSA skill. Students must use >= (not >) for the threshold comparison and must not modify the original lists.
Part B tests finding the index of a maximum value in a list, then using that index to remove corresponding elements from two parallel lists. The key subtlety is using strictly greater than when updating maxIndex so that ties resolve to the earliest occurrence. Students must remove from both lists using the same index, and must save the title before removing it.
Education Coach Advice
AP Exam Strategy:
- For parallel-list problems, always use an index-based
forloop so you can access both lists at the same index simultaneously. - When building a filtered list, create the new
ArrayListat the top of the method and return it at the bottom — don't forget thereturnstatement. - For "find and remove the max" problems, find the index first, save what you need, then remove. Never remove inside the search loop.
- Trace your code with the given example before moving on — it takes 30 seconds and catches most off-by-one and operator errors.
- Remember:
ArrayList.remove(int index)removes by position; make sure you're not accidentally callingremove(Object).
Traps
Part A traps:
- Using
>instead of>=for the threshold check — would exclude books rated exactly at the threshold. - Modifying the original
titleslist instead of building a new one. - Using an enhanced for-each loop over
titleswithout tracking the index, making it impossible to look up the corresponding rating.
Part B traps:
- Using
>=instead of>when updatingmaxIndex— this would cause ties to resolve to the last occurrence rather than the first. - Forgetting to remove the element from one of the two lists.
- Removing from
titlesfirst and then trying to remove fromratingsat the same index — this is actually fine since both use the same savedmaxIndex, but students who re-calltitles.indexOf(...)after removal may get the wrong index. - Not saving the title string before calling
remove().
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.

