What this quiz covers
This quiz focuses on Implementing 2d Array Algorithms, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
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?
AP Computer Science a Quiz
Practice Implementing 2d Array Algorithms in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.
This quiz focuses on Implementing 2d Array Algorithms, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.
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?
Explanation: 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.
A spiral traversal algorithm visits elements of an m×n matrix in clockwise spiral order, starting from the top-left corner. Which condition correctly determines when to change direction during the traversal?
Explanation: Option A correctly describes the condition: change direction when continuing would either exceed array bounds or revisit a cell. This handles both rectangular and square matrices correctly. Option B incorrectly uses min(m,n)/2 which doesn't account for the varying lengths of spiral sides. Option C mentions boundary values but doesn't specify the correct logic for when those boundaries are reached. Option D is close but doesn't clearly specify how to detect when a side is completed - the actual test is bounds/visited cells.
The following method attempts to find the number of islands in a 2D binary array, where 1 represents land and 0 represents water. Islands are formed by connected 1s (horizontally or vertically adjacent).
public static int countIslands(int[][] grid) { if (grid == null || grid.length == 0) return 0; int count = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == 1) { count++; markIsland(grid, i, j); } } } return count; }
Which implementation of the markIsland helper method would correctly support the island counting algorithm above?
Explanation: 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.
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?
Explanation: 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.
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?
Explanation: 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.
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?
Explanation: 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.
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?
Explanation: 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 [[0, 1], [2, 3], [4, 5], [6, 7]], what is the resulting matrix after transposing into a new int[][]?
Explanation: This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically transposing a non-square matrix. Transposition converts a matrix with dimensions m×n to n×m by making rows into columns and columns into rows. In this scenario, the original array [[0, 1], [2, 3], [4, 5], [6, 7]] has 4 rows and 2 columns, so the transpose will have 2 rows and 4 columns. Choice B ([[0, 2, 4, 6], [1, 3, 5, 7]]) is correct because the first column [0, 2, 4, 6] becomes the first row, and the second column [1, 3, 5, 7] becomes the second row. Choice A shows the original array, while C and D show incorrect transformations. To help students: Create a new array with swapped dimensions first, then systematically copy elements where newArray[j][i] = originalArray[i][j]. Watch for: Students often forget to create a new array with the correct dimensions or mix up the index mapping.
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?
Explanation: 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 [[2,5,9],[1,4,7]], what is the resulting matrix after transposing the array into a new 2D array?
Explanation: This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding matrix transposition where rows become columns and vice versa. 2D array transposition requires creating a new array with swapped dimensions and systematically copying elements such that element at position [i][j] moves to position [j][i]. In this scenario, the array operation requires transposing the 2x3 matrix [[2,5,9],[1,4,7]] into a 3x2 matrix. Choice A ([[2,1],[5,4],[9,7]]) is correct because each column of the original matrix becomes a row in the transposed matrix: first column [2,1] becomes first row, second column [5,4] becomes second row, and third column [9,7] becomes third row. Choice B shows the original array unchanged, while choices C and D show incorrect element arrangements. To help students: Draw the transformation visually with arrows showing element movement, emphasize that dimensions swap (rows×cols becomes cols×rows), and practice with non-square matrices. Watch for: Students often confuse transposition with simply reshaping or fail to swap the array dimensions correctly.
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)?
Explanation: 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 [[8,2,5],[1,9,3],[4,7,6]], what is the resulting matrix after swapping row 0 with row 2?
Explanation: 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, for int[][] grid = {{2,8,-3},{4,0,6}}, what is the output of a method that returns the sum of all elements?
Explanation: 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.
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?
Explanation: 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, transpose int[][] t = {{3,-2},{5,7},{0,4}} into a new array; what is the resulting matrix?
Explanation: 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, transpose int[][] m = {{1,2,3},{4,5,6}} into a new array; what is the resulting matrix?
Explanation: 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.
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?
Explanation: 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 [[8, 3, 1], [4, 9, 6], [7, 0, 2]], what is the resulting matrix after swapping rows 0 and 2?
Explanation: This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding row swapping operations in a 2D array. 2D arrays store data in rows and columns, and swapping rows involves exchanging entire rows of data while maintaining the column structure. In this scenario, we need to swap row 0 ([8, 3, 1]) with row 2 ([7, 0, 2]) in the array [[8, 3, 1], [4, 9, 6], [7, 0, 2]]. Choice A ([[7, 0, 2], [4, 9, 6], [8, 3, 1]]) is correct because it shows row 2 moved to position 0, row 1 unchanged in the middle, and row 0 moved to position 2. Choice B incorrectly reverses the entire array order, while choices C and D show different incorrect transformations. To help students: Visualize row swapping as exchanging entire horizontal strips of the array, and practice with physical cards or drawings to understand the operation. Watch for: Students often confuse row and column indices or attempt to swap individual elements instead of entire rows.
Based on the provided 2D array [[1, 2, 3], [4, 5, 6]], what is the resulting matrix after transposing the array into a new int[][]?
Explanation: This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically understanding matrix transposition. Transposing a matrix involves converting rows to columns and columns to rows, effectively reflecting the matrix along its main diagonal. In this scenario, the original array [[1, 2, 3], [4, 5, 6]] has 2 rows and 3 columns, so the transposed result will have 3 rows and 2 columns. Choice B ([[1, 4], [2, 5], [3, 6]]) is correct because element at position [i][j] in the original becomes element at position [j][i] in the transpose: the first column [1, 4] becomes the first row, second column [2, 5] becomes the second row, and third column [3, 6] becomes the third row. Choice A shows the original array unchanged, while C and D show incorrect transformations. To help students: Draw the original matrix and its transpose side by side, connecting corresponding elements with arrows to visualize the transformation. Watch for: Students often confuse transposition with other operations like rotation or reflection, or forget to create a new array with swapped dimensions.
Based on the provided 2D array [[2, 5, 2], [9, 2, 1]], what is the resulting matrix after replacing every 2 with 7?
Explanation: This question tests AP Computer Science A skills in implementing 2D array algorithms, specifically replacing specific values throughout a 2D array. This operation requires traversing the entire array and checking each element for the target value, then replacing it with the new value. In this scenario, we need to replace every occurrence of 2 with 7 in the array [[2, 5, 2], [9, 2, 1]]. Choice A ([[7, 5, 7], [9, 7, 1]]) is correct because it shows all three occurrences of 2 (at positions [0][0], [0][2], and [1][1]) replaced with 7, while other values remain unchanged. Choice B shows the original array unchanged, C misses one replacement, and D shows an incorrect pattern. To help students: Systematically traverse the array using nested loops and test each element individually, updating in-place or creating a new array as required. Watch for: Students often miss occurrences of the target value or accidentally modify non-target values.