Leaders in an Array
Problem and examples
Given an array of integers, your task is to find all the leader elements in the array.
- A leader is an element that is greater than all the elements to its right in the array.
- The rightmost element is always a leader because there are no elements after it.
You need to return a list of all such leaders in left-to-right order as they appear in the array.
| Input Array | Leaders | Description |
|---|---|---|
| [16, 17, 4, 3, 5, 2] | [17, 5, 2] | 17 > [4,3,5,2], 5 > 2, and 2 is last so it's a leader |
| [1, 2, 3, 4, 5] | [5] | Only 5 is greater than all elements to its right (none) |
| [5, 4, 3, 2, 1] | [5, 4, 3, 2, 1] | Each element is greater than all elements to its right |
| [7] | [7] | Single element is always a leader |
| [] | [] | Empty array, so no leaders |
| [10, 10, 10] | [10] | Only the last occurrence is considered a leader |
| [0, -1, -2, -3] | [0, -1, -2, -3] | All elements are leaders in descending order |
Explore Find Leaders in an Array
Load an example or enter your own input. Use the player controls to follow each change.
Understanding the Problem
We are given an array of integers, and we are asked to find all the leaders in the array.
A leader is defined as an element that is strictly greater than all the elements to its right.
This means we need to check, for each element, whether there is any greater element after it. If not, it's a leader.
Why start from the end?
The last element in the array has no elements after it. So, it is always a leader.
We will scan the array from right to left, keeping track of the current maximum. Every time we find a number greater than this maximum, we consider it a new leader.
Step-by-Step Approach (With Example)
Let’s take the example [16, 17, 4, 3, 5, 2] and go through the solution step by step.
- Start from the last element:
2. It has no elements to its right, so it’s a leader. - Next element to the left:
5. Since5 > 2, it’s a leader. Update the current maximum to 5. - Next:
3. Since3 < 5, it is NOT a leader. - Next:
4. Since4 < 5, it is NOT a leader. - Next:
17. Since17 > 5, it is a leader. Update the current maximum to 17. - Finally:
16. Since16 < 17, it is NOT a leader.
We collected the leaders in reverse order: [2, 5, 17]. So we reverse the list to get the final answer: [17, 5, 2].
Handling Edge Cases
- Increasing Array:
[1, 2, 3, 4, 5]– Only the last element5is a leader. - Decreasing Array:
[5, 4, 3, 2, 1]– All elements are leaders since each is greater than those after it. - Equal Elements:
[10, 10, 10]– Only the last one is a leader. Leaders must be strictly greater. - Single Element:
[7]– The only element is always a leader. - Empty Array:
[]– No elements, so no leaders. Return an empty list.
Final Explanation
To solve the problem efficiently, we scan the array once from right to left, maintaining a max_so_far variable. Every time we find an element greater than max_so_far, we add it to our list of leaders.
Since we find leaders from the right side, we reverse the list at the end to maintain the original left-to-right order.
This gives us an efficient solution with O(n) time complexity and O(n) space complexity (for storing leaders).
- Given an array
arr. - Initialize an empty list
leadersto store leader elements. - Start from the last element: initialize
max_from_right = arr[n-1]. - Add
max_from_rightto theleaderslist. - Traverse the array from right to left:
- → If current element is greater than
max_from_right, updatemax_from_rightand add it toleaders. - After the loop, reverse the
leaderslist to maintain left-to-right order.
Implementation and efficiency
C implementation
#include <stdio.h>
void findLeaders(int arr[], int n) {
int maxFromRight = arr[n - 1];
int leaders[n], k = 0;
leaders[k++] = maxFromRight;
for (int i = n - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i];
leaders[k++] = maxFromRight;
}
}
printf("Leaders: ");
for (int i = k - 1; i >= 0; i--) {
printf("%d ", leaders[i]);
}
printf("\n");
}
int main() {
int arr[] = {16, 17, 4, 3, 5, 2};
int n = sizeof(arr) / sizeof(arr[0]);
findLeaders(arr, n);
return 0;
}C++ implementation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> findLeaders(vector<int>& arr) {
int n = arr.size();
vector<int> leaders;
int maxFromRight = arr[n - 1];
leaders.push_back(maxFromRight);
for (int i = n - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i];
leaders.push_back(maxFromRight);
}
}
reverse(leaders.begin(), leaders.end());
return leaders;
}
int main() {
vector<int> arr = {16, 17, 4, 3, 5, 2};
vector<int> result = findLeaders(arr);
cout << "Leaders: ";
for (int num : result) cout << num << " ";
return 0;
}Python implementation
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
arr = [16, 17, 4, 3, 5, 2]
print("Leaders:", find_leaders(arr))Java implementation
import java.util.*;
public class LeadersInArray {
public static List<Integer> findLeaders(int[] arr) {
int n = arr.length;
List<Integer> leaders = new ArrayList<>();
int maxFromRight = arr[n - 1];
leaders.add(maxFromRight);
for (int i = n - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i];
leaders.add(maxFromRight);
}
}
Collections.reverse(leaders);
return leaders;
}
public static void main(String[] args) {
int[] arr = {16, 17, 4, 3, 5, 2};
System.out.println("Leaders: " + findLeaders(arr));
}
}JavaScript implementation
function findLeaders(arr) {
let n = arr.length;
let leaders = [];
let maxFromRight = arr[n - 1];
leaders.push(maxFromRight);
for (let i = n - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i];
leaders.push(maxFromRight);
}
}
leaders.reverse();
return leaders;
}
const arr = [16, 17, 4, 3, 5, 2];
console.log("Leaders:", findLeaders(arr));Go implementation
package main
import (
"fmt"
)
func findLeaders(arr []int) []int {
n := len(arr)
leaders := []int{}
maxFromRight := arr[n-1]
leaders = append(leaders, maxFromRight)
for i := n - 2; i >= 0; i-- {
if arr[i] > maxFromRight {
maxFromRight = arr[i]
leaders = append(leaders, maxFromRight)
}
}
// Reverse the leaders slice
for i, j := 0, len(leaders)-1; i < j; i, j = i+1, j-1 {
leaders[i], leaders[j] = leaders[j], leaders[i]
}
return leaders
}
func main() {
arr := []int{16, 17, 4, 3, 5, 2}
result := findLeaders(arr)
fmt.Print("Leaders: ")
for _, val := range result {
fmt.Printf("%d ", val)
}
fmt.Println()
}Rust implementation
fn find_leaders(arr: &Vec<i32>) -> Vec<i32> {
let n = arr.len();
let mut leaders = vec![];
let mut max_from_right = arr[n - 1];
leaders.push(max_from_right);
for i in (0..n - 1).rev() {
if arr[i] > max_from_right {
max_from_right = arr[i];
leaders.push(max_from_right);
}
}
leaders.reverse();
leaders
}
fn main() {
let arr = vec![16, 17, 4, 3, 5, 2];
let leaders = find_leaders(&arr);
print!("Leaders: ");
for val in leaders {
print!("{} ", val);
}
println!();
}Kotlin implementation
fun findLeaders(arr: IntArray): List<Int> {
val leaders = mutableListOf<Int>()
var maxFromRight = arr.last()
leaders.add(maxFromRight)
for (i in arr.size - 2 downTo 0) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i]
leaders.add(maxFromRight)
}
}
leaders.reverse()
return leaders
}
fun main() {
val arr = intArrayOf(16, 17, 4, 3, 5, 2)
println("Leaders: ${findLeaders(arr)}")
}Swift implementation
func findLeaders(_ arr: [Int]) -> [Int] {
var leaders = [Int]()
var maxFromRight = arr.last!
leaders.append(maxFromRight)
for i in stride(from: arr.count - 2, through: 0, by: -1) {
if arr[i] > maxFromRight {
maxFromRight = arr[i]
leaders.append(maxFromRight)
}
}
return leaders.reversed()
}
let arr = [16, 17, 4, 3, 5, 2]
print("Leaders:", findLeaders(arr))TypeScript implementation
function findLeaders(arr: number[]): number[] {
let leaders: number[] = [];
let maxFromRight = arr[arr.length - 1];
leaders.push(maxFromRight);
for (let i = arr.length - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i];
leaders.push(maxFromRight);
}
}
leaders.reverse();
return leaders;
}
const arr: number[] = [16, 17, 4, 3, 5, 2];
console.log("Leaders:", findLeaders(arr));Time complexity
| Case | Time | Explanation |
|---|---|---|
| best case | O(n) | The array is scanned from right to left once, and each element is checked only once, making the operation linear. |
| average case | O(n) | Regardless of input distribution, the array is always scanned once from end to start to compare with the running maximum. |
| worst case | O(n) | In the worst case (e.g., strictly decreasing array), every element becomes a leader, but the time taken remains linear as there is still only one pass. |
Space complexity
O(n)
The worst-case space is O(n) if all elements are leaders and stored in the list. Additional space is used only for the leaders list and a few variables.