OA. free
Free
Accenture Data Structures & Algorithms Data Structures & Algorithms Medium

This Java function receives an input of array of integers arr and outputs true if there are...

Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.

This Java function receives an input of array of integers arr and outputs true if there are any neighboring array elements that have the same value in the array.

For example:

  • Given arr = {0, 3, 2, 2, 6, -1, 3}, the elements 2, 2 are next to each other and are the same value, so true is returned.
  • Given arr = {0, 3, 2, 5, 6, -1, 3}, there are no elements with the same values next to each other, so false is returned.
static boolean containConsecutive(int[] arr) {
    for (int i = 0; i < [ ① ]; i++) {
        if ([ ② ]) {
            return true;
        }
    }
    return false;
}

Choose the appropriate formula to enter into [ ① ] [ ② ] to make the function work.

Choose one option.
Show answer & explanation
Answer: B. [ ① ] arr.length-1 [ ② ] arr[i] == arr[i+1]

To check consecutive pairs, we need to iterate from index 0 to arr.length-1 (not arr.length, which would cause an out-of-bounds error when checking arr[i+1]). We compare arr[i] with arr[i+1] to check if neighboring elements are equal. Option B correctly uses arr.length-1 as the loop bound and arr[i] == arr[i+1] to compare consecutive elements.

Step-by-step Derivation:
Step-by-step trace:

  1. Loop bound: If we use arr.length-1, the last iteration is i = arr.length-2, allowing safe access to arr[i+1] = arr[arr.length-1].
  2. If we used arr.length, at i = arr.length-1, accessing arr[i+1] would be out of bounds.
  3. Comparison: arr[i] == arr[i+1] checks if the current element equals the next element (forward comparison).
  4. Example: arr = {0, 3, 2, 2, 6, -1, 3}
    • i=0: arr[0]=0, arr[1]=3, not equal
    • i=1: arr[1]=3, arr[2]=2, not equal
    • i=2: arr[2]=2, arr[3]=2, EQUAL → return true ✓

Option A fails because arr[i-1] when i=0 causes out-of-bounds.
Options C and D use arr.length, which would cause out-of-bounds when accessing arr[i+1].