Problem statement

Leaders in an array Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader.

Example

Input array = [16, 17, 4, 3, 5, 2] 
output:  17, 5, 2.

Approach 1

brute force implementation

#collapse-hide
from typing import List

class Solution:
    def findLeaders(self, nums: List[int]) -> int:
        result = []
        for i in range(len(nums)):
            flag = 0
            for j in range(i+1, len(nums)):
                if nums[i] < nums[j]:
                    # print(nums[i], " < ", nums[j])
                    flag = 1
                if flag == 1:
                    break
            if flag == 0:
                # print(nums[i])
                result.append(nums[i])
        return result
sol = Solution()
sol.findLeaders([1, 2, 3, 4])
[4]
sol.findLeaders([8, 4, 2, 3, 1, 5, 4, 2])
[8, 5, 4, 2]
sol.findLeaders([10, 6, 3, 1, 7, 9])
[10, 9]

Worst case performance in Time: $O(n^2)$

Approach 2

Traversing from End

Image source GeekForGeeks

#collapse-hide
class Solution:
    def findLeaders(self, nums: List[int]) -> int:
        j = nums[len(nums)-1]
        result = []
        for i in range(len(nums)-1, -1, -1):
            if nums[i] >= j:
                j = nums[i]
                result.append(j)
        return result[::-1]
sol = Solution()
sol.findLeaders([1, 2, 3, 4])
[4]
sol.findLeaders([8, 4, 2, 3, 1, 5, 4, 2])
[8, 5, 4, 2]
sol.findLeaders([10, 6, 3, 1, 7, 9])
[10, 9]

Twin

#collapse-hide
import sys

def findLeaders(arr,n):
    max_value=-sys.maxsize -1
    for i in range(n-1,-1,-1):
        if(max_value<arr[i]):
            max_value=arr[i]
            print(max_value)
        
findLeaders([16, 17, 4, 3, 5, 2],6)     
2
5
17

Worst case performance in Time: $O(n)$