Unit 4 Cycle 2 Day 24: Array: Consecutive Duplicates
Share
Array: Consecutive Duplicates
Section 4.3 — Common Array Algorithms
Key Concept
Detecting consecutive duplicates compares adjacent elements using arr[i] == arr[i + 1] (for primitives) or arr[i].equals(arr[i + 1]) (for objects). The loop must stop at arr.length - 1 to avoid an out-of-bounds error. The AP exam tests variations: counting runs of duplicates, finding the longest run, or removing consecutive duplicates. For the longest run, track both the current run length and the maximum run length seen so far, resetting the current when consecutive elements differ.
Consider the following method.
For which array does the method return true?
Answer: (B) {1, 2, 3, 3}
{1,2,3,3}: arr[2]==arr[3] (3==3), returns true. Others have no adjacent equal elements.
Why Not the Others?
(A) 1 appears twice but not adjacent (separated by 2).
(C) No duplicates at all.
(D) No adjacent equals in descending sequence.
Common Mistake
"Consecutive duplicates" = adjacent equal elements. {1,2,1} has duplicates but NOT consecutive ones.
AP Exam Tip
Adjacent checking: loop to length-1, compare arr[i] with arr[i+1]. Finds consecutive patterns only.