Data Structure FRQ
Solve free-response tasks involving arrays, ArrayLists, or 2D arrays with careful traversal and mutation logic.
A lesson of AP Computer Science A, in Arrays, ArrayLists, and 2D Arrays, about 10 minutes.
Data Structures FRQ: Arrays and ArrayLists
By the end of this lesson, you will be able to write FRQ-quality code manipulating arrays and ArrayLists, avoiding common errors.
FRQ Part 1 or 2: Array/ArrayList Methods
AP Computer Science A FRQs frequently ask you to:
- Traverse an array or ArrayList
- Find/count elements meeting a condition
- Modify elements
- Return a new array/ArrayList filtered from another
Template: Traversal and Accumulation
// Sum all positive elements in an array
public static int sumPositive(int[] arr) {
int sum = 0;
for (int val : arr) {
if (val > 0) {
sum += val;
}
}
return sum;
}
Template: Find the Maximum (with Index)
public static int indexOfMax(int[] arr) {
int maxIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
Never initialize max to 0 — initialize it to arr[0]. If all values are negative, max = 0 would give the wrong answer.
Template: Build a New ArrayList from a Condition
// Return a new ArrayList of all strings with length > 5
public static ArrayList<String> longWords(ArrayList<String> words) {
ArrayList<String> result = new ArrayList<String>();
for (String w : words) {
if (w.length() > 5) {
result.add(w);
}
}
return result;
}
Removing While Iterating (Tricky!)
// WRONG:
for (String s : list) {
if (s.equals("bad")) list.remove(s); // ConcurrentModificationException
}
// CORRECT: iterate backwards with index
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).equals("bad")) list.remove(i);
}
WRONG: removing from an ArrayList while using a for-each loop causes errors.
Template: 2D Array Processing
// Find the sum of each row in a 2D array
public static int[] rowSums(int[][] matrix) {
int[] sums = new int[matrix.length];
for (int row = 0; row < matrix.length; row++) {
int rowSum = 0;
for (int col = 0; col < matrix[row].length; col++) {
rowSum += matrix[row][col];
}
sums[row] = rowSum;
}
return sums;
}
Common FRQ Pitfalls
| Mistake | Fix |
|---|---|