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

A JavaScript function searches for an integer x in an array of length N by iterating from...

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

A JavaScript function searches for an integer x in an array of length N by iterating from index 0 to length - 1. What is the worst-case time complexity of this search?

Choose one option.
Show answer & explanation
Answer: C. O(N)

Linear search examines each element sequentially from index 0 to length - 1, so in the worst case (element not found or at the end), it must check all N elements. This results in O(N) time complexity. Options A and B are incorrect because the search cannot guarantee finding the element in constant or logarithmic time without additional properties like a sorted array. Option D (O(N²)) would only apply if the search involved nested iterations.

Step-by-step Derivation:
Linear Search Algorithm Analysis:

  1. The function iterates through the array once: for (let i = 0; i < N; i++)
  2. In each iteration, it performs a constant-time comparison: array[i] === x
  3. Number of iterations in worst case: N (when x is not in array or is at the last position)
  4. Total operations: N × 1 = N
  5. Therefore, worst-case time complexity = O(N)

Example: Searching for value 99 in [1, 2, 3, ..., 98]

  • Must check all N elements before concluding 99 is not present
  • Comparisons performed: N