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?
Show answer & explanation
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:
- The function iterates through the array once: for (let i = 0; i < N; i++)
- In each iteration, it performs a constant-time comparison: array[i] === x
- Number of iterations in worst case: N (when x is not in array or is at the last position)
- Total operations: N × 1 = N
- 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