Leaders in an Array
Pattern: Traversal and in-place tricks
An element is a leader if it is bigger than everything to its right. Walk from the right and keep the biggest value seen so far.
The problem
You are given an array of between 1 and 100,000 whole numbers. An element is a leader if it is strictly bigger than every
element to its right. The last element always counts as a leader. Return all leaders in their original left-to-right
order. For example, the leaders of [16, 17, 4, 3, 5, 2] are [17, 5, 2].
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name leaders, the "strictly bigger" rule and the limits are this guide's own.
Think first
- To decide whether
nums[i]is a leader, which single value about the right-hand side do you need? - If you walk from the left, can you know that value yet? What if you walk from the right?
- Walking from the right finds the leaders in reverse order. How do you fix that?
Hints
Brute force, and why it fails
For each element, scan everything to its right and check it is bigger than all of it. That is O(n²): for 100,000 elements, about 5 billion comparisons.
The key insight
Information about "everything to the right" is free if you walk from the right: one running maximum answers it for every position in turn.
Dry run
| maxToRight | 2 |
|---|---|
| found | [2] |
nums = [16, 17, 4, 3, 5, 2]. Walk from the right. The last element has nothing to its right, so 2 is a leader.
The plan
result = empty list
for i from n - 1 down to 0:
if result is empty or nums[i] > last value in result: # last value = max to the right
append nums[i] to result
reverse result # found right to left
return result
Complexity
- Time
O(n)- Space
O(n)
One pass from the right plus one reverse. The result list can hold up to n values (for a strictly decreasing array).
Edge cases
- One element: it is a leader.
- Strictly increasing, as in
[1, 2, 3]: only the last element is a leader. - Strictly decreasing, as in
[3, 2, 1]: every element is a leader. - Equal values, as in
[7, 7, 7]: only the last one, because "strictly bigger" fails for the others.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> leaders(int[] nums) {
List<Integer> result = new ArrayList<>();
int maxToRight = Integer.MIN_VALUE;
boolean first = true; // the last element is always a leader
for (int i = nums.length - 1; i >= 0; i--) {
if (first || nums[i] > maxToRight) {
result.add(nums[i]);
maxToRight = nums[i];
first = false;
}
}
Collections.reverse(result); // we collected them right to left
return result;
}
}C++
class Solution {
public:
vector<int> leaders(vector<int>& nums) {
vector<int> result;
int n = static_cast<int>(nums.size());
for (int i = n - 1; i >= 0; i--) {
if (result.empty() || nums[i] > result.back()) { // result.back() is the max to the right
result.push_back(nums[i]);
}
}
reverse(result.begin(), result.end()); // we collected them right to left
return result;
}
};Python
class Solution:
def leaders(self, nums):
result = []
for i in range(len(nums) - 1, -1, -1):
if not result or nums[i] > result[-1]: # result[-1] is the max to the right
result.append(nums[i])
result.reverse() # we collected them right to left
return resultCommon mistakes
- Walking from the left and rescanning the right side for every element.
- Forgetting to reverse, which returns the leaders right to left.
- Using
>=instead of>, which counts equal values as leaders.