Implementing ArrayList Algorithms - AP Computer Science A

  1. An ArrayList named data contains [5, 10, 15, 20]. What are the contents of data after the call Swapper.swap(data, 1, 3)?
    Answer: [5, 20, 15, 10] The swap method exchanges the elements at the specified indices i and j. The call swap(data, 1, 3) will swap the element at index 1 (which is 10) with the element at index 3 (which is 20). The resulting list will be [5, 20, 15, 10].
  2. An ArrayList wordList contains ["the", "quick", "brown", "fox", "jumps"]. What are the contents of the ArrayList returned by the call ListFilter.filterByLength(wordList, 5)?
    Answer: ["quick", "brown", "jumps"] The method creates a new ArrayList and adds only those strings from the input list that have a length equal to the parameter len. In this case, len is 5. The words "quick", "brown", and "jumps" each have a length of 5 and are added to the result list, which is then returned.
  3. Consider the following method that processes an ArrayList<Integer>: public static ArrayList<Integer> mystery(ArrayList<Integer> list) { ArrayList<Integer> result = new ArrayList<Integer>(); for (int i = 0; i < list.size(); i++) { boolean found = false; for (int j = 0; j < result.size(); j++) { if (list.get(i).equals(result.get(j))) { found = true; break; } } if (!found) { result.add(list.get(i)); } } return result; } What does this method accomplish?
    Answer: Returns a new ArrayList containing only the unique elements from the original list, preserving their first occurrence order When you encounter code tracing problems on the AP Computer Science A exam, you need to carefully follow the algorithm step by step to understand what it accomplishes. This method creates a new ArrayList called result and iterates through each element in the input list. For each element, it checks whether that element already exists in the result list using a nested loop. The inner loop searches through result to see if the current element has already been added. If the element isn't found (found remains false), it gets added to result. If it is found, the method skips adding it and moves to the next element. This process ensures that each unique value appears exactly once in the result, maintaining the order of first occurrence. For example, if the input is [3, 1, 4, 1, 5, 3, 2], the method would return [3, 1, 4, 5, 2]. Choice A is incorrect because the method doesn't reverse the order—it preserves the original sequence of first occurrences. Choice B is wrong because there's no sorting happening; elements maintain their original relative positions. Choice C incorrectly suggests the method finds elements that appear exactly once in the original list, but it actually keeps the first occurrence of every element, regardless of how many times it appears. The correct answer is D because the method removes duplicates while preserving the order of first appearances. Strategy tip: When tracing algorithms, follow the code line by line with a concrete example. Pay attention to what each loop accomplishes and how variables change throughout execution.
  4. If the method is called with removeGreater(myList, 5) where myList initially contains [3, 7, 2, 8, 4, 9, 1], what will myList contain after the method executes?
    Answer: [3, 2, 8, 4, 1] The correct answer is C. This method has a bug - it removes elements while iterating forward, causing indices to shift. When i=1, it removes 7, shifting 8 left. When i=2, it checks 8 (not 2), removes it, shifting 9 left. When i=4, it checks 9, removes it. Elements 2, 4, 1 are never checked because of index shifting. Choice A would be correct if the algorithm worked properly. Choice B assumes nothing is removed. Choice D shows partial removal without the index shifting effect.
  5. Consider an ArrayList<Integer> named data. Which of the following code segments will correctly rotate the elements of the list one position to the right (i.e., the last element becomes the first, and all other elements shift one position to the right)?
    Answer: if (data.size() > 1) { Integer temp = data.remove(data.size() - 1); data.add(0, temp); } The correct answer is B. The remove method returns the element being removed, so this efficiently removes the last element and adds it to the front in two operations. Choice A is incorrect because it gets the element but doesn't use the return value of remove, making it less efficient but functionally equivalent. Choice C is incorrect because after adding the last element to the front, the list size increases, so removing at data.size()-1 removes the wrong element. Choice D is correct in logic but unnecessarily complex, using a loop to shift elements when ArrayList's add and remove methods handle this automatically.
  6. Which of the following methods correctly implements an algorithm to reverse the elements of an ArrayList<String> in place (modifying the original list rather than creating a new one)?
    Answer: public static void reverse(ArrayList<String> list) { for (int i = 0; i < list.size() / 2; i++) { String temp = list.get(i); list.set(i, list.get(list.size() - 1 - i)); list.set(list.size() - 1 - i, temp); } } When you encounter ArrayList reversal problems, you're dealing with the classic "swap from both ends" algorithm. The key insight is that you only need to swap elements from the first half of the list with their corresponding elements from the second half. Let's examine why option D works correctly. It loops from index 0 to less than list.size() / 2, which ensures you only process the first half of the elements. For each position i, it swaps the element at index i with the element at index list.size() - 1 - i (its mirror position from the end). The three-line swap using a temporary variable correctly exchanges the values without losing data. Option A has a critical flaw: the loop condition uses <= instead of < with list.size() / 2. This means when the list has an odd number of elements, the middle element gets swapped with itself, which is unnecessary but harmless. However, this creates an off-by-one error in the logic. Option B is fundamentally broken because it processes the entire list rather than just half. This means every swap gets undone when the loop reaches the second half, leaving the list unchanged. Option C uses Collections.reverse(list), which would work perfectly in practice, but since this appears to be testing your understanding of implementing the algorithm yourself, it's not the intended answer. Remember: when implementing in-place reversal algorithms, always process only half the elements to avoid undoing your swaps. The loop should run while i < list.size() / 2.
  7. An ArrayList named numbers contains [1, 2, 3, 4, 5]. What are the contents of numbers after the call Reverser.reverseList(numbers)?
    Answer: [5, 4, 3, 2, 1] The method implements an in-place reversal algorithm. It iterates through the first half of the list, swapping each element with its corresponding element from the end of the list. It swaps index 0 with 4, and index 1 with 3. The middle element at index 2 is not moved. The result is the list in reverse order: [5, 4, 3, 2, 1].
  8. An ArrayList named data contains [10, 20, 15, 25, 20]. What is returned by PairCounter.countIncreasingPairs(data)?
    Answer: 2 The method counts the number of adjacent pairs where the first element is less than the second. The pairs are (10, 20), (20, 15), (15, 25), and (25, 20). The increasing pairs are (10, 20) and (15, 25). Therefore, the method returns a count of 2.
  9. Based on the scenario above, which line correctly initializes an ArrayList to store daily temperatures as integers?
    Answer: ArrayList<Integer> temps = new ArrayList<Integer>(); This question tests AP Computer Science A skills, specifically using ArrayLists to implement and analyze algorithms. ArrayLists in Java provide dynamic sizing and random access capabilities, making them suitable for various algorithmic problems requiring flexible data storage and manipulation. In this scenario, the task involves correctly initializing an ArrayList to store integer values, which requires understanding Java's type system and generics. Choice B is correct because ArrayLists cannot store primitive types directly, so we must use the wrapper class Integer instead of int, and proper generic syntax requires specifying the type in angle brackets. Choice A is incorrect because ArrayList<int> is invalid syntax - Java generics require reference types, not primitives like int. To help students: Explain the difference between primitive types and their wrapper classes. Emphasize that collections in Java can only store objects, not primitives, necessitating autoboxing.
  10. Which of the following can replace /* missing code */ so that the method works as intended?
    Answer: return i; The method is designed to return the index of the first match. Inside the loop, when list.get(i) equals target, the current index i should be returned immediately. return i; accomplishes this. break; would exit the loop, but the method would then execute return -1;, which is incorrect. return list.get(i); returns a String, which is the wrong return type. indexOf is not available on ArrayList and is what the method is implementing.
  11. An ArrayList of String objects named words is initialized with ["cat", "mouse", "snake", "elephant", "dog"]. What are the contents of words after the call ListCleaner.removeLongWords(words)?
    Answer: ["cat", "snake", "dog"] This method has a common bug. When an element is removed from an ArrayList while traversing with a standard forward for-loop, the subsequent element shifts to the current index, but the loop counter i still increments, causing that shifted element to be skipped. mouse (length 5) is removed, and snake shifts into its index. The loop increments i, skipping snake. Then elephant (length 8) is removed. The final list is ["cat", "snake", "dog"].
  12. If this method is called on an ArrayList containing ["a", "b", "b", "c", "c", "c", "d"], what will the ArrayList contain after the method executes?
    Answer: ["a", "b", "c", "c", "d"] The correct answer is C. The algorithm has a bug: when it removes an element, the subsequent elements shift left, but the loop counter i still increments, causing some duplicates to be skipped. Starting with ["a", "b", "b", "c", "c", "c", "d"]: i=1 compares "b"=="a" (false), i=2 compares "b"=="b" (true, removes second "b"), i=3 compares "c"=="c" (true, removes first "c"), i=4 compares "c"=="c" (true, removes second "c"), i=5 compares "d"=="c" (false). Result: ["a", "b", "c", "c", "d"]. Choice A would be correct if the algorithm worked properly. Choice B shows partial removal. Choice D shows an impossible result.
  13. Which of the following ArrayLists would cause the method hasDuplicates to return true? I. ["a", "b", "c", "d"] II. ["a", "b", "c", "a"] III. ["a", "a", "b", "c"]
    Answer: II and III only The method returns true if any element appears more than once. List I has no duplicates and will return false. List II has a duplicate "a" at the beginning and end, so it will return true. List III has a duplicate "a" at the first two positions, so it will return true. Therefore, both II and III will cause the method to return true.
  14. An ArrayList of Person objects named roster contains three objects with the following attributes: (Name: "Ann", Age: 25), (Name: "Ben", Age: 30), (Name: "Cora", Age: 25). What is returned by the call RosterUtil.findOldest(roster)?
    Answer: "Ben" The method implements a standard algorithm to find the maximum value. It iterates through the ArrayList, keeping track of the Person object with the highest age found so far. In the given list, Ben has the maximum age of 30. The method returns the name of this Person object, which is "Ben".
  15. Using the given problem statement, which line of code correctly initializes the ArrayList for this problem?
    Answer: ArrayList<Integer> scores = new ArrayList<>(); This question tests AP Computer Science A skills, specifically using ArrayLists to implement and analyze algorithms. ArrayLists in Java provide dynamic sizing and random access capabilities, making them suitable for various algorithmic problems requiring flexible data storage and manipulation. In this scenario, the task requires correctly initializing an ArrayList to store Integer objects, which involves understanding Java's syntax for generics and the distinction between primitive types and wrapper classes. Choice B is correct because it uses the proper generic syntax ArrayList<Integer> for the wrapper class (not the primitive int), and employs the diamond operator <> on the right side, which is the modern Java syntax for type inference. Choice A is incorrect because ArrayList cannot directly store primitive types like int; it requires the Integer wrapper class to store numeric values. To help students: Explain the difference between primitive types and wrapper classes in the context of collections. Practice writing ArrayList declarations for different data types and emphasize modern Java syntax conventions.
  16. Which of the following code segments can replace /* missing code */ so the method works as intended?
    Answer: Both B and C would work as intended. The goal is to remove the first element and add it to the end. Option B correctly removes the element at index 0, stores it in a variable, and then adds that variable to the end of the list. Option C achieves the same result more concisely by passing the return value of list.remove(0) directly to the list.add() method. Option A is incorrect because get(0) does not remove the element, resulting in a duplicate. Since both B and C are correct, D is the best answer.
  17. If this method is called with insertSorted(myList, 6) where myList initially contains [1, 3, 5, 7, 9], what will be the state of myList after the method executes?
    Answer: [1, 3, 5, 6, 7, 9] The correct answer is A. The method correctly finds the insertion point by incrementing i while elements are less than the target value. Starting with i=0: list.get(0)=1 < 6 (true), i=1; list.get(1)=3 < 6 (true), i=2; list.get(2)=5 < 6 (true), i=3; list.get(3)=7 < 6 (false), loop exits. Then list.add(3, 6) inserts 6 at index 3, resulting in [1, 3, 5, 6, 7, 9]. Choice B would occur if the comparison was <= instead of <. Choice C would occur if the method always appended to the end. Choice D would occur if the method always inserted at the beginning.
  18. Which of the following methods correctly implements a binary search algorithm for a sorted ArrayList<Integer>? The method should return the index of the target value, or -1 if not found.
    Answer: public static int binarySearch(ArrayList<Integer> list, int target) { int left = 0, right = list.size() - 1; while (left <= right) { int mid = (left + right) / 2; if (list.get(mid) == target) return mid; else if (list.get(mid) < target) left = mid + 1; else right = mid - 1; } return -1; } The correct answer is A. This implements the standard binary search correctly: uses left <= right for the loop condition, properly updates left = mid + 1 and right = mid - 1, and uses == for Integer comparison. Choice B has incorrect loop bounds (right starts at size() instead of size()-1). Choice C uses left < right but then needs an extra check after the loop. Choice D has bugs: it sets left = mid and right = mid instead of mid ± 1, which can cause infinite loops, and unnecessarily uses .equals() for Integer comparison.
  19. What code should replace the comment "// Missing code here" to complete the merge method correctly?
    Answer: if (i < list1.size()) { result.addAll(list1.subList(i, list1.size())); } if (j < list2.size()) { result.addAll(list2.subList(j, list2.size())); } The correct answer is B. After the main while loop exits, one list may still have remaining elements that need to be added to the result. Choice B uses subList and addAll to efficiently append any remaining elements. Choice A is also functionally correct using while loops. Choice C is functionally correct using for loops. Choice D is incorrect because it uses i+1 and j+1, which would skip the elements at the current indices i and j.
  20. An ArrayList named data contains [10, 20, 30, 40, 50]. What are the contents of data after the call Rotator.rotateRight(data)?
    Answer: [50, 10, 20, 30, 40] The method performs a right rotation. The last element (50) is removed from the end of the list, which becomes [10, 20, 30, 40]. Then, the removed element (50) is inserted at index 0. The final state of the list is [50, 10, 20, 30, 40].

Start this quiz