- Based on the provided 2D array, transpose int[][] m = {{1,2,3},{4,5,6}} into a new array; what is the resulting matrix?
Answer: {{1,4},{2,5},{3,6}}
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding matrix transposition where rows become columns and columns become rows. 2D arrays can be transformed through transposition, which involves creating a new array where element at position [i][j] in the original becomes element at position [j][i] in the transposed array. In this scenario, the array operation requires transposing the 2x3 matrix {{1,2,3},{4,5,6}} into a 3x2 matrix where the first row {1,2,3} becomes the first column and the second row {4,5,6} becomes the second column. Choice B is correct because it accurately shows the transposed result {{1,4},{2,5},{3,6}}, where each original row has been converted to a column in the new matrix. Choice A is incorrect because it simply returns the original matrix unchanged, indicating a fundamental misunderstanding of what transposition means. To help students: Use visual diagrams showing how rows map to columns, practice with different sized matrices to reinforce dimension changes, and emphasize that transpose creates a new array with swapped dimensions. Watch for: Students often confuse transposition with other operations like rotation or reflection, or forget to create a new array with swapped dimensions.
- Consider a method that finds the maximum sum of elements in any single row of a 2D integer array. Which implementation correctly handles all edge cases?
Answer: public static int maxRowSum(int[][] arr) {
int maxSum = Integer.MIN_VALUE;
for (int r = 0; r < arr.length; r++) {
int rowSum = 0;
for (int c = 0; c < arr[r].length; c++) {
rowSum += arr[r][c];
}
maxSum = Math.max(maxSum, rowSum);
}
return maxSum;
}
Option A correctly initializes maxSum to Integer.MIN_VALUE to handle arrays with all negative values, uses arr[r].length for the inner loop to handle jagged arrays, and initializes rowSum to 0 for proper summation. Option B fails with all-negative arrays due to initializing maxSum to 0. Option C uses arr.length instead of arr[r].length in the inner loop, causing index out of bounds errors in jagged arrays. Option D incorrectly initializes rowSum to Integer.MIN_VALUE, making the first addition incorrect.
- Based on the provided 2D array, transpose int[][] t = {{3,-2},{5,7},{0,4}} into a new array; what is the resulting matrix?
Answer: {{3,5,0},{-2,7,4}}
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding matrix transposition with non-square matrices. 2D arrays can be transposed regardless of their dimensions, converting an m×n matrix to an n×m matrix where rows become columns and vice versa. In this scenario, the array operation requires transposing the 3x2 matrix {{3,-2},{5,7},{0,4}} into a 2x3 matrix where each row becomes a column in the new array. Choice A is correct because it shows the transposed result {{3,5,0},{-2,7,4}}, where the first column {3,5,0} becomes the first row and the second column {-2,7,4} becomes the second row. Choice B is incorrect because it maintains the original dimensions (3x2) instead of creating the transposed dimensions (2x3), showing a fundamental misunderstanding of transposition. To help students: Emphasize dimension changes in transposition, use index mapping [i][j] → [j][i], and practice with various rectangular matrices. Watch for: Students often forget to create a new array with swapped dimensions or confuse the index mapping during transposition.
- Based on the provided 2D array, for int[][] grid = {{2,8,-3},{4,0,6}}, what is the output of a method that returns the sum of all elements?
Answer: 17
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically calculating the sum of all elements in a 2D array. 2D arrays store data in rows and columns, and summing all elements requires iterating through each row and column to accumulate values. In this scenario, the array operation requires adding all elements in the matrix {{2,8,-3},{4,0,6}}, which means calculating 2+8+(-3)+4+0+6. Choice A is correct because it accurately computes the sum: 2+8-3+4+0+6 = 17, properly handling the negative value and zero in the calculation. Choice B (23) is incorrect because it likely results from treating the negative value as positive (2+8+3+4+0+6=23), a common error when students overlook negative signs. To help students: Emphasize careful attention to negative numbers, practice nested loop iteration patterns for 2D arrays, and use trace tables to track running sums during iteration. Watch for: Students often miss negative signs or make arithmetic errors when mentally calculating sums, so encourage systematic calculation approaches.
- Consider a method that finds all cells in a 2D grid that are local maxima (greater than all adjacent neighbors, including diagonals). Which edge case handling is most critical for correctness?
Answer: Ensuring that cells on the border or corners are compared only with their existing neighbors, not with out-of-bounds positions.
When working with 2D arrays and algorithms that examine neighboring cells, boundary conditions are your primary concern. The core challenge is ensuring your algorithm doesn't attempt to access array indices that don't exist.
Option C correctly identifies the most critical edge case: you must validate that you're only comparing cells with neighbors that actually exist in the array. When checking if a cell is a local maximum, corner cells have only 3 neighbors, edge cells have 5 neighbors, and interior cells have 8 neighbors. Attempting to access grid[-1][0] or grid[rows][0] will cause an ArrayIndexOutOfBoundsException, immediately crashing your program. This makes boundary checking absolutely essential for basic functionality.
Option A is wrong because local maxima can be meaningfully identified in grids smaller than 3×3. A single cell in a 1×1 grid is trivially a local maximum, and 2×2 grids can have valid local maxima.
Option B misunderstands the definition of local maxima. By definition, a local maximum must be greater than (not equal to) all neighbors. Treating equal values as maxima would be mathematically incorrect.
Option D suggests an optimization that's both unnecessary and incorrect. Pre-sorting would destroy the spatial relationships between cells that are fundamental to the local maxima concept. The algorithm must preserve the original grid structure.
Remember: when processing 2D arrays with neighbor-checking algorithms, always validate array bounds first. Use conditions like if (row >= 0 && row < rows && col >= 0 && col < cols) before accessing any cell.
- A method transposes a rectangular m×n matrix in-place when possible, or indicates when additional space is required. Which condition determines when in-place transposition is feasible?
Answer: In-place transposition is only possible when the matrix is square (m = n), otherwise the dimensions change and additional space is required.
When you encounter matrix transposition problems, think about what happens to the matrix dimensions and how elements need to move. Matrix transposition swaps rows and columns, so an m×n matrix becomes an n×m matrix after transposition.
In-place transposition means performing this operation without allocating additional memory for a new matrix. For this to work, the original matrix storage space must be able to accommodate the transposed result. An m×n matrix has dimensions m rows by n columns, but after transposition, it needs to fit n rows by m columns in the same memory space.
This is only possible when m = n (a square matrix), because then the dimensions remain the same after transposition: an n×n matrix becomes an n×n matrix. You can swap elements across the diagonal without changing the overall structure. For non-square matrices, the row and column counts change, making it impossible to fit the result back into the original space.
Option A incorrectly suggests that powers of 2 enable in-place transposition through bit manipulation, but bit operations don't solve the fundamental dimension mismatch problem. Option B wrongly claims that having m×n be a perfect square allows rearrangement in cycles - while cycle-based algorithms exist for some cases, they don't resolve the dimension incompatibility. Option C incorrectly states that divisibility between dimensions enables proper cycle decomposition, but this doesn't address the core issue of fitting different dimensions in the same space.
Remember: in-place operations require the result to fit exactly where the original data was stored. For matrix transposition, this only works when dimensions don't change.
- Based on the provided 2D array, replace every 0 with 9 in int[][] board = {{0,1,0},{2,0,3}}; what is the resulting matrix?
Answer: {{9,1,9},{2,9,3}}
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically replacing specific values throughout a 2D array. 2D arrays can be modified by iterating through all elements and replacing values that match a specific condition, requiring nested loops to access each element. In this scenario, the array operation requires replacing every 0 with 9 in the matrix {{0,1,0},{2,0,3}}, which means changing elements at positions [0][0], [0][2], and [1][1] from 0 to 9. Choice A is correct because it shows all three zeros replaced with 9s, resulting in {{9,1,9},{2,9,3}}, maintaining all non-zero values unchanged. Choice B is incorrect because it shows some zeros remaining unchanged, suggesting incomplete iteration or conditional logic errors in the replacement algorithm. To help students: Practice writing nested loops with conditional statements, use trace tables to track which elements are modified, and emphasize testing with arrays containing multiple target values. Watch for: Students often miss some occurrences of the target value due to loop boundary errors or incorrect conditional logic.
- Based on the provided 2D array [[3,8,1],[6,4,9],[7,2,5]], what is the resulting matrix after swapping column 0 with column 2?
Answer: [[1,8,3],[9,4,6],[5,2,7]]
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding how to swap entire columns in a 2D array. 2D array column swapping is more complex than row swapping because it requires iterating through all rows and swapping individual elements at the specified column indices. In this scenario, the array operation requires swapping column 0 with column 2 in the matrix [[3,8,1],[6,4,9],[7,2,5]]. Choice A ([[1,8,3],[9,4,6],[5,2,7]]) is correct because in each row, the first element (column 0) and last element (column 2) are exchanged while the middle element (column 1) remains unchanged. Choice B shows a complete reversal, choice C shows incorrect element positioning, and choice D shows a different transformation. To help students: Visualize column swapping as exchanging vertical strips element by element, practice with loop implementations that swap arr[i][0] with arr[i][2], and emphasize that middle columns remain unchanged. Watch for: Students often confuse column swapping with row swapping or attempt to swap column references directly.
- A method rotates a square 2D array 90 degrees clockwise. After the rotation, element at position (i, j) in the original array should be at position (j, n-1-i) where n is the array dimension. What is the correct approach to implement this in-place rotation?
Answer: Swap elements in concentric square layers, processing each layer from outside to inside, performing 4-way swaps for each position in the current layer boundary.
Option A correctly describes the layer-by-layer approach needed for in-place rotation, where elements are swapped in groups of 4 to avoid overwriting values before they're moved. Option B would overwrite values before they're properly relocated. Option C requires extra space and isn't in-place. Option D describes a valid rotation algorithm but transposes first then reverses rows, which is a different approach than the layer-based method needed for the given transformation formula.
- Consider an algorithm that finds the largest rectangular area of 1s in a binary 2D array. The algorithm processes each row as the base of potential rectangles and uses a histogram-based approach. Which statement best describes the time complexity bottleneck?
Answer: The histogram processing for each row using a stack-based algorithm contributes O(n) per row, leading to O(mn) overall complexity.
Option B correctly identifies that the histogram processing using a stack-based approach (like largest rectangle in histogram) takes O(n) time per row, and with m rows, gives O(mn) total complexity, which is optimal. Option A describes basic array traversal but misses the histogram processing complexity. Option C incorrectly suggests O(m²n) complexity - the consecutive 1s calculation can be done incrementally in O(1) per cell. Option D describes a brute force approach that isn't used in efficient histogram-based algorithms.
- Based on the provided 2D array [[8,2,5],[1,9,3],[4,7,6]], what is the resulting matrix after swapping row 0 with row 2?
Answer: [[4,7,6],[1,9,3],[8,2,5]]
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding how to swap entire rows in a 2D array. 2D arrays allow row-level operations where entire rows can be exchanged by reassigning row references, which is more efficient than swapping individual elements. In this scenario, the array operation requires swapping row 0 ([8,2,5]) with row 2 ([4,7,6]) in the matrix [[8,2,5],[1,9,3],[4,7,6]]. Choice A ([[4,7,6],[1,9,3],[8,2,5]]) is correct because it shows row 0 and row 2 properly exchanged while row 1 remains unchanged. Choice B incorrectly shows the original array with rows in reverse order, while choices C and D show various incorrect transformations. To help students: Visualize row swapping as exchanging entire horizontal strips, practice with array reference diagrams, and emphasize that middle rows remain unchanged in pairwise swaps. Watch for: Students often confuse row swapping with reversing the entire array or accidentally modify unchanged rows.
- Based on the provided 2D array, compute diagonal difference for int[][] a = {{11,2,4},{4,5,6},{10,8,-12}}; what is the output of abs(primarySum-secondarySum)?
Answer: 15
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically calculating the diagonal difference in a square matrix. 2D arrays can have two diagonals in square matrices: the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left), and the diagonal difference is the absolute value of their sums' difference. In this scenario, the array operation requires computing diagonal sums for {{11,2,4},{4,5,6},{10,8,-12}}, where primary diagonal is 11+5+(-12)=4 and secondary diagonal is 4+5+10=19. Choice B is correct because it accurately computes |4-19|=|-15|=15, properly handling the negative element in the primary diagonal and taking the absolute value of the difference. Choice A (10) is incorrect and might result from calculation errors or misidentifying diagonal elements. To help students: Use visual highlighting of diagonal elements, practice identifying diagonals in different sized square matrices, and emphasize the importance of the absolute value operation. Watch for: Students often confuse which diagonal is primary vs secondary, forget to take absolute value, or make arithmetic errors with negative numbers.
- Based on the provided 2D array [[1, 4, 7], [2, 5, 8], [3, 6, 9]], what is the resulting matrix after swapping columns 0 and 2?
Answer: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically swapping columns in a 2D array. Column swapping involves exchanging entire vertical strips of data, which requires iterating through all rows and swapping elements at the specified column indices. In this scenario, we need to swap column 0 with column 2 in the array [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. Choice A ([[7, 4, 1], [8, 5, 2], [9, 6, 3]]) is correct because in each row, the element at index 0 is swapped with the element at index 2: row 0 becomes [7, 4, 1], row 1 becomes [8, 5, 2], and row 2 becomes [9, 6, 3]. Choice B shows a different transformation, while C and D show partial or incorrect swaps. To help students: Visualize column swapping as exchanging vertical strips and practice by highlighting the columns to be swapped before performing the operation. Watch for: Students often confuse column swapping with row swapping or only swap elements in some rows.
- Based on the provided 2D array [[11,2,4],[4,5,6],[10,8,-12]], what is the output of a method computing diagonal absolute difference?
Answer: 15
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding diagonal difference calculations in square matrices. 2D arrays have two main diagonals: the primary diagonal (top-left to bottom-right where row index equals column index) and the secondary diagonal (top-right to bottom-left where row + column equals size - 1). In this scenario, the array operation requires computing the absolute difference between diagonal sums for [[11,2,4],[4,5,6],[10,8,-12]]. Choice A (15) is correct because the primary diagonal sum is 11 + 5 + (-12) = 4, the secondary diagonal sum is 4 + 5 + 10 = 19, and |4 - 19| = 15. Choice B (-15) represents the non-absolute difference, while other choices show calculation errors. To help students: Draw both diagonals clearly on the matrix, practice identifying diagonal elements using index patterns, and emphasize the absolute value operation. Watch for: Students often confuse which diagonal is which, forget the absolute value, or miscalculate with negative numbers.
- Which implementation of the
markIsland helper method would correctly support the island counting algorithm above? Answer: private static void markIsland(int[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] != 1) return;
grid[i][j] = 0;
markIsland(grid, i+1, j); markIsland(grid, i-1, j);
markIsland(grid, i, j+1); markIsland(grid, i, j-1);
}
When you encounter graph traversal problems like island counting, you're dealing with a classic depth-first search (DFS) pattern. The key insight is that once you find a land cell (value 1), you need to "mark" all connected land cells so they won't be counted as separate islands later.
The correct implementation (D) works perfectly because it checks all necessary boundary conditions before proceeding. It verifies that coordinates are within bounds (i >= 0, i < grid.length, j >= 0, j < grid[i].length) and that the current cell contains land (grid[i][j] == 1). When these conditions are met, it marks the cell as visited by setting it to 0, then recursively explores all four adjacent directions.
Looking at the incorrect options: Choice A has a structural flaw—it checks if the cell equals 1 inside the method rather than in the base case condition, which could lead to unnecessary recursive calls. Choice B uses grid[0].length instead of grid[i].length, which assumes all rows have the same length and could cause index errors in jagged arrays. Choice C marks visited cells with -1 instead of 0, but since the main algorithm only looks for cells equal to 1, this would work—however, it's less clean than using 0 to represent "processed water."
The critical insight is that grid[i].length (not grid[0].length) handles jagged 2D arrays correctly, and the base case must check grid[i][j] != 1 to stop recursion immediately when hitting water or already-processed cells. Remember: in DFS problems, always validate boundaries first, then check your termination condition.
- Based on the provided 2D array, for int[][] nums = {{-2,4},{6,1},{0,-3}}, what is the output of a method that returns the sum of all elements?
Answer: 6
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically calculating the sum of all elements in a 2D array with mixed positive and negative values. 2D arrays require nested iteration to access all elements, and summing operations must correctly handle both positive and negative integers. In this scenario, the array operation requires adding all elements in the matrix {{-2,4},{6,1},{0,-3}}, which means calculating (-2)+4+6+1+0+(-3). Choice A is correct because it accurately computes the sum: -2+4+6+1+0-3 = 6, properly handling both negative values and zero in the calculation. Choice B (10) is incorrect because it likely results from ignoring one of the negative signs, possibly calculating -2+4+6+1+0+3=12 or making another arithmetic error. To help students: Use systematic row-by-row summation, maintain a running total variable, and double-check arithmetic with negative numbers. Watch for: Students often make sign errors with negative numbers or skip elements due to incorrect loop boundaries.
- Based on the provided 2D array [[5,1,5],[2,5,3],[4,0,5]], what is the resulting matrix after replacing every 5 with 9?
Answer: [[9,1,9],[2,9,3],[4,0,9]]
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding element replacement operations across an entire 2D array. 2D array element replacement requires traversing all positions using nested loops and conditionally modifying elements that match specific criteria. In this scenario, the array operation requires replacing every occurrence of 5 with 9 in the matrix [[5,1,5],[2,5,3],[4,0,5]]. Choice A ([[9,1,9],[2,9,3],[4,0,9]]) is correct because it shows all four occurrences of 5 (at positions [0][0], [0][2], [1][1], and [2][2]) replaced with 9, while all other elements remain unchanged. Choice B incorrectly leaves some 5s unchanged, choice C mixes replacements inconsistently, and choice D over-replaces non-5 elements. To help students: Trace through each element systematically, use debugging print statements to verify replacements, and emphasize that only exact matches should be replaced. Watch for: Students often miss some occurrences, accidentally modify non-matching elements, or use incorrect comparison operators.
- A method searches for a target sum by finding two elements in different rows of a sorted 2D matrix (each row sorted ascending, first element of each row greater than last element of previous row). What is the optimal approach?
Answer: For each element in the matrix, use binary search to find if (target - element) exists in any other row, achieving O(mn log n) complexity.
Option C correctly identifies the optimal approach: for each element, binary search other rows for the complement value. This gives O(mn log n) complexity. Option A's approach is unclear about how pairs are checked and likely less efficient. Option B treats it as a flattened array but doesn't leverage the constraint that elements must be in different rows, and two-pointer on flattened array doesn't respect the row constraint. Option D describes the standard 2D matrix search technique but doesn't address the different-rows constraint or how to find pairs summing to target.
- Based on the provided 2D array [[1,2],[3,4],[5,6],[7,8]], what is the resulting matrix after transposing into a new array?
Answer: [[1,3,5,7],[2,4,6,8]]
This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding matrix transposition with non-square arrays. 2D array transposition transforms an m×n matrix into an n×m matrix by making rows into columns and columns into rows, requiring careful attention to dimension changes. In this scenario, the array operation requires transposing the 4×2 matrix [[1,2],[3,4],[5,6],[7,8]] into a 2×4 matrix. Choice A ([[1,3,5,7],[2,4,6,8]]) is correct because the first column [1,3,5,7] becomes the first row and the second column [2,4,6,8] becomes the second row, properly transforming the 4×2 array into a 2×4 array. Choice B shows the original array, choice C shows an incorrect 2×4 arrangement, and choice D shows a reversal rather than transposition. To help students: Use grid paper to visualize the transformation, emphasize that element at [i][j] moves to [j][i], and practice with various rectangular matrices. Watch for: Students often forget to create a new array with swapped dimensions or confuse transposition with other transformations.
- An algorithm performs a flood fill operation on a 2D character array, replacing all connected cells of the same character with a new character. Using a recursive approach, which modification would be most effective in preventing stack overflow for large connected regions?
Answer: Replace the recursive approach with an iterative approach using an explicit stack or queue to manage cells to be processed.
Option B correctly identifies that replacing recursion with iteration eliminates the call stack depth limit, preventing stack overflow in large connected regions. Option A helps with efficiency but doesn't address stack overflow from deep recursion. Option C misunderstands the problem - flood fill already marks visited cells to avoid redundancy, and memoization doesn't reduce recursion depth. Option D would complicate the algorithm significantly and wouldn't guarantee completing the flood fill operation.