Leaders in an Array - Optimal Approach

Leaders in an Array - Optimal Approach

Algorithm Steps

  1. Given an array arr.
  2. Initialize an empty list leaders to store leader elements.
  3. Start from the last element: initialize max_from_right = arr[n-1].
  4. Add max_from_right to the leaders list.
  5. Traverse the array from right to left:
  6. → If current element is greater than max_from_right, update max_from_right and add it to leaders.
  7. 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))