OA. free
Free
Accenture Core Computer Science Core Computer Science 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 containsConsecutive(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 detect consecutive equal elements, we need to compare each element with its next neighbor. The loop must iterate only to arr.length-1 because at that point we compare arr[i] with arr[i+1], and accessing arr[arr.length] would cause an ArrayIndexOutOfBoundsException. Option B correctly uses arr[i] == arr[i+1] to check consecutive pairs.

Step-by-step Derivation:
Step-by-step analysis:

  1. Loop bound (①): If we iterate to arr.length, the condition arr[i] == arr[i+1] when i = arr.length-1 would access arr[arr.length], which is out of bounds. So we must use arr.length-1.

  2. Comparison condition (②): We need to compare consecutive elements. Starting from i=0, we compare arr[i] with arr[i+1]. This checks each pair: (arr[0], arr[1]), (arr[1], arr[2]), ..., (arr[arr.length-2], arr[arr.length-1]).

  3. Verification with example 1: arr = {0, 3, 2, 2, 6, -1, 3}

    • i=0: arr[0]==arr[1]? (0==3) → false
    • i=1: arr[1]==arr[2]? (3==2) → false
    • i=2: arr[2]==arr[3]? (2==2) → true ✓ (returns true)
  4. Verification with example 2: arr = {0, 3, 2, 5, 6, -1, 3}

    • Loop completes without finding equal consecutive elements → returns false ✓
  5. Why other options fail:

    • Option A: arr[i] == arr[i-1] when i=0 accesses arr[-1], causing an error.
    • Option C: arr.length allows i=arr.length-1, making arr[i+1] access arr[arr.length], out of bounds.
    • Option D: Same issue as C—loop goes too far.