OA. free
Free
Accenture Core Computer Science Core Computer Science Medium

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

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

for (int i = 0; i < l % []; i++) {
    if (l == [])) {
        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]`

The function detects consecutive duplicate elements in an array. ① should be arr.length-1 because when comparing arr[i] with arr[i+1], the loop must stop before the last index to avoid an out-of-bounds access. ② should be arr[i] == arr[i+1] to check if the current element equals the next element, identifying consecutive duplicates.

Step-by-step Derivation:
Corrected Code Analysis:

for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] == arr[i+1]) {
        return true;
    }
}
return false;

Step-by-step:

  1. Loop Condition [ ① ]: When accessing arr[i+1] inside the if statement, the maximum valid index is arr.length - 1. Therefore, i must go from 0 to arr.length - 2, making the condition i < arr.length - 1.

    • Option A/B use arr.length - 1
    • Option C/D use arr.length ✗ (would cause IndexOutOfBoundsException when i = arr.length - 1)
  2. Comparison [ ② ]: The function checks for consecutive equal elements:

    • Option B: arr[i] == arr[i+1] compares current with next element ✓
    • Option A/C: arr[i] == arr[i-1] compares current with previous element (less common pattern for this loop structure) ✗

Example Trace (arr = [1, 2, 2, 3]):

  • i=0: arr[0]=1 vs arr[1]=2 → false
  • i=1: arr[1]=2 vs arr[2]=2 → true → return true ✓