Consider an algorithm that processes an array of n elements by performing two passes: the first pass checks a condition on each element, and the second pass, only if a certain flag is set, scans the entire array again.
- A. O(n) in all cases
- D. O(log n) in the best case and O(n) in the worst case
- C. O(n) in the best case and O(n^2) in the worst case
- B. O(n^2) in all cases
Vote, then reply with how you reasoned it out. The answer goes up in about a day.
This is a clean case of a potential two-pass with a conditional second pass. The first pass always runs O(n). The second pass runs O(n) only if the flag is set; in the worst case, that makes the total O(n) + O(n) = O(n). So the overall time complexity is O(n) in all cases (best and worst align here since the second pass may or may not run, but never exceeds a single extra linear pass).
For a quick reference on how to reason about combined steps like this, check out the kirupa article on Big-O intuition for multiple passes: