Leaders in an array — Asked in Goldman Sachs, Microsoft and Adobe Interview

Placewit
2 min readJun 11, 2021

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)

Code :

Thanks for Reading

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.

--

--