Array Leaders
Array Leaders is a easy arrays & hashing problem solved with the right to left traversal pattern.
The best approach, optimal (right-to-left max), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force up.
Problem
An element is a leader if it is greater than or equal to every element to its right. The rightmost element is always a leader. Return all leaders in the order they appear in the array.
Examples
Example 1
- Input
arr = [10, 4, 2, 4, 1]- Output
[10, 4, 4, 1]- Why
- 10 beats everything after it; the second 4 ties nothing larger after it; 1 is last.
Example 2
- Input
arr = [5, 7, 3]- Output
[7, 3]
Constraints
1 <= arr.length <= 10^60 <= arr[i] <= 10^6- An element is a leader if it is greater than or equal to every element to its right.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force | O(n²) | O(1) |
| Optimal (right-to-left max) | O(n) | O(1) |
1Brute force
O(n²)O(1)Besides the output list.For each element, scan everything to its right and check that nothing is larger.
- For each i, check arr[j] <= arr[i] for all j > i.
- Collect i if the check passes.
class Solution {
static ArrayList<Integer> leaders(int[] arr) {
ArrayList<Integer> out = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
boolean leader = true;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] > arr[i]) { leader = false; break; }
if (leader) out.add(arr[i]);
}
return out;
}
}class Solution:
def leaders(self, arr: List[int]) -> List[int]:
out = []
for i in range(len(arr)):
leader = True
for j in range(i + 1, len(arr)):
if arr[j] > arr[i]:
leader = False
break
if leader:
out.append(arr[i])
return outclass Solution {
public:
vector<int> leaders(vector<int>& arr) {
vector<int> out;
int n = arr.size();
for (int i = 0; i < n; i++) {
bool leader = true;
for (int j = i + 1; j < n; j++)
if (arr[j] > arr[i]) { leader = false; break; }
if (leader) out.push_back(arr[i]);
}
return out;
}
};function leaders(arr) {
const out = [];
for (let i = 0; i < arr.length; i++) {
let leader = true;
for (let j = i + 1; j < arr.length; j++)
if (arr[j] > arr[i]) { leader = false; break; }
if (leader) out.push(arr[i]);
}
return out;
}2Optimal (right-to-left max)
O(n)O(1)Besides the output list.Traverse from the right with the maximum seen so far. An element is a leader when it is at least that maximum. Collect leaders in reverse, then reverse the list to restore the original order.
- max = -infinity.
- For i from n - 1 to 0: if arr[i] >= max, add it and set max = arr[i].
- Reverse the collected list.
class Solution {
static ArrayList<Integer> leaders(int[] arr) {
ArrayList<Integer> out = new ArrayList<>();
int max = Integer.MIN_VALUE;
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] >= max) {
out.add(arr[i]);
max = arr[i];
}
}
Collections.reverse(out);
return out;
}
}class Solution:
def leaders(self, arr: List[int]) -> List[int]:
out = []
mx = float('-inf')
for i in range(len(arr) - 1, -1, -1):
if arr[i] >= mx:
out.append(arr[i])
mx = arr[i]
out.reverse()
return outclass Solution {
public:
vector<int> leaders(vector<int>& arr) {
vector<int> out;
int mx = INT_MIN;
for (int i = (int) arr.size() - 1; i >= 0; i--) {
if (arr[i] >= mx) {
out.push_back(arr[i]);
mx = arr[i];
}
}
reverse(out.begin(), out.end());
return out;
}
};function leaders(arr) {
const out = [];
let max = -Infinity;
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] >= max) {
out.push(arr[i]);
max = arr[i];
}
}
out.reverse();
return out;
}Edge cases to test
- The last element is always a leader
- Equal values (>= counts as a leader)
- A strictly increasing array has only one leader
Hints
Hint 1
Walk from the right while tracking the maximum seen so far.
FAQ
What is the best time complexity for Array Leaders?
Optimal (right-to-left max) runs in O(n) time and O(1) extra space.
Which pattern does Array Leaders use?
It is a arrays & hashing problem that uses the right to left traversal pattern. Other problems with the same pattern: Product of Array Except Self, Next Permutation, Buildings With an Ocean View.
Is there a brute force solution for Array Leaders?
Yes. Brute force takes O(n²) time and O(1) space. For each element, scan everything to its right and check that nothing is larger.
Which edge cases should I test for Array Leaders?
The last element is always a leader; Equal values (= counts as a leader); A strictly increasing array has only one leader.