Algorithm Steps
- Given an array
arr
. - Initialize an empty list
leaders
to store leader elements. - Start from the last element: initialize
max_from_right = arr[n-1]
. - Add
max_from_right
to theleaders
list. - Traverse the array from right to left:
- → If current element is greater than
max_from_right
, updatemax_from_right
and add it toleaders
. - After the loop, reverse the
leaders
list to maintain left-to-right order.
Find All Leaders in an Array (Right to Left Scan) Code
Python
JavaScript
Java
C++
C
def find_leaders(arr):
n = len(arr)
leaders = []
max_from_right = arr[-1]
leaders.append(max_from_right)
for i in range(n - 2, -1, -1):
if arr[i] > max_from_right:
max_from_right = arr[i]
leaders.append(max_from_right)
leaders.reverse()
return leaders
# Sample Input
arr = [16, 17, 4, 3, 5, 2]
print("Leaders:", find_leaders(arr))