An element in an array is called a leader if it is greater than all elements to the right of it in . The best algorithm to find all leaders in an array
View worked solution
Answer: B
An element is a leader if it is greater than all elements to its right, i.e., for all .
We can find all leaders efficiently by scanning the array from right to left:
- The rightmost element is always a leader because there are no elements to its right. We initialize
max_so_farwith . - We traverse the array from index down to .
- For each element , if , then is a leader. We then update .
- If , it is not a leader.
This approach requires only a single pass from right to left, performing a constant number of operations at each step. Thus, the time complexity is (linear time) and the auxiliary space complexity is .
Why other options are incorrect/suboptimal:
- Option A: A simple left-to-right pass cannot determine if an element is a leader without knowing the maximum of the remaining elements to its right, which would require lookaheads or auxiliary data structures.
- Option C and D: While divide-and-conquer or a naive approach can solve the problem, they are not the best (most optimal) algorithms since is achievable.
Free practice · Your answers on this page are not saved.
