Explorer
Data Structures & Algorithms

Find all elements that are strictly greater than all elements to their right.

Problem Statement

Given an array `arr` of integers, find all the leaders in the array. An element is called a leader if it is greater than or equal to all elements to its right side. The rightmost element is always a leader. Return the leaders in the order they appear from left to right.

Examples

Input: arr = [16, 17, 4, 3, 5, 2]

Output: [17, 5, 2]

Explanation: 17 is greater than 4, 3, 5, 2. 5 is greater than 2. 2 has no elements to its right.

Input: arr = [1, 2, 3, 4, 0]

Output: [4, 0]

Explanation: Elements in [4, 0] are greater than all elements to their right.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: An element is a leader if it is greater than or equal to all elements to its right. šŸ’” Hint 2: Scanning from right to left allows tracking the current maximum element to the right in O(1). šŸ’” Hint 3: Whenever arr[i] >= maxFromRight, it is a leader. Collect and reverse at the end.

Editorial & Approach

Problem Overview & Intuition

Checking from left to right would require an O(N) search for each element (O(N²)). By traversing from right to left, we maintain maxFromRight in O(1) time per element.

Step-by-Step Approach

  1. Initialize result = [] and maxFromRight = -Infinity.
  2. Iterate i from arr.length - 1 down to 0.
  3. If arr[i] >= maxFromRight, push arr[i] to result and update maxFromRight = arr[i].
  4. Reverse result to maintain original left-to-right order, then return it.

Optimal Implementation (JavaScript)

function leaders(arr) {
  const result = [];
  let maxFromRight = -Infinity;
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] >= maxFromRight) {
      result.push(arr[i]);
      maxFromRight = arr[i];
    }
  }
  return result.reverse();
}

Complexity Analysis

Time Complexity O(N) — single traversal plus reversal.
Space Complexity O(1) auxiliary space (excluding output array).

Edge Cases & Corner Traps Handled

  • The last element is always a leader.
  • Strictly increasing array: only the last element is leader.
  • Strictly decreasing array: every element is a leader.

Leaders in an Array

Medium
Given an array `arr` of integers, find all the leaders in the array. An element is called a leader if it is greater than or equal to all elements to its right side. The rightmost element is always a leader. Return the leaders in the order they appear from left to right.
Example Scenarios
1Example 1
Input: arr = [16, 17, 4, 3, 5, 2]
Output: [17, 5, 2]
Explanation:

17 is greater than 4, 3, 5, 2. 5 is greater than 2. 2 has no elements to its right.

2Example 2
Input: arr = [1, 2, 3, 4, 0]
Output: [4, 0]
Explanation:

Elements in [4, 0] are greater than all elements to their right.

Editor
Loading Editor...
arr =
[16, 17, 4, 3, 5, 2]
Output:Click "Run" above to execute and verify your code here.
[17,5,2]