Leaders in Array in Java: Explanation & Practice

Find all leaders in an array

Problem summary

A leader is an element greater than all elements to its right. Rightmost is always a leader.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {16, 17, 4, 3, 5, 2}; // Test case 1
        
        // Find and print leaders (right to left order)
        // Print space-separated
    }
}

Expected output and test cases

  • Leaders in [16,17,4,3,5,2]
    2 5 17
  • Descending = all leaders
    4 3 2 1
  • Ascending = only last
    5

Hints

  1. Start from rightmost element
  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