Leaders in an array — Asked in Goldman Sachs, Microsoft and Adobe Interview
Problem Statement :
Given a sequence of numbers. Find all leaders in sequence. An element is a leader if it is strictly greater than all the elements on its right side.
Note:
Rightmost element is always a leader.
Sample Input:
13, 14, 3, 8, 2
Sample Output:
14, 8, 2
Approach :
- Start iterating from right to left in the sequence.
- Keep the highest element in a variable ‘maximum’.
- If we find any element greater than the variable ‘maximum’ then update the ‘maximum’ variable to the current element and add the current element in the answer sequence.
- Finally, return the answer sequence.
Time Complexity : O(N)
Space Complexity : O(M)