Find Leaders in Java: Explanation & Practice

Find elements greater than all elements to their right

Problem summary

A leader is an element greater than all elements to its right. Find all leaders in the array.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {16, 17, 4, 3, 5, 2}; // Test case 1
        
        // Print leaders (rightmost is always a leader)
        // Print result space-separated
    }
}

Expected output and test cases

  • Leaders in [16,17,4,3,5,2]
    17 5 2
  • Descending array - all are leaders
    5 4 3 2 1
  • Ascending array - only last is leader
    5

Hints

  1. Traverse from right to left
  2. Track maximum seen so far
  3. If current > max, it's a leader

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler