Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Array Leaders | Optimal Solution in Python
    Data Structures & Algorithms

    Array Leaders | Optimal Solution in Python

    Anirudh KhuranaBy Anirudh Khurana29 June 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to find leaders in array
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Given an array arr[] of size n, an element is called an Array Leaders if it is greater than or equal to every element on its right.
    Your task is to return all leaders in their original left-to-right order.

    Here’s the [Problem Link] to begin with.

    Quick Examples

    Input arrayLeaders (output)Why?
    [16, 17, 4, 3, 5, 2][17, 5, 2]17 ≥ 4…2, 5 ≥ 2, last element 2 is always a leader
    [7, 10, 4, 10, 6, 5, 2][10, 10, 6, 5, 2]Scan from right: 2 (leader) → 5 ≥ 2 → 6 ≥ 5…
    [1, 2, 3][3]Only the right-most element meets the condition

    The naive idea would be to check every element against everything to its right (O(n²)), but we can do better in one backward pass.


    Optimal Solution (Right-to-Left Scan)

    Intuition and Approach

    • Sweeping from the right keeps track of the maximum value seen so far (maxi).
    • Every time the current element arr[i] is ≥ maxi, it means nothing to its right is larger, so arr[i] is a leader.
    • Update maxi whenever a new leader is found.
    • Collect leaders in a list while moving right → left, then reverse that list to restore left-to-right order.

    This achieves the goal in one linear pass with constant extra space.

    Code Implementation

    class Solution:
        def leaders(self, arr):
            n = len(arr)
            maxi = float("-inf")   # holds the greatest element seen so far (to the right)
            result = []            # stores leaders found during the scan (right ➜ left)
    
            # Traverse array from right to left
            for i in range(n - 1, -1, -1):
                if arr[i] >= maxi:
                    result.append(arr[i])      # current element is a leader
                    maxi = max(maxi, arr[i])   # update the running maximum
    
            result.reverse()        # restore original ordering
            return result

    Code Explanation

    1. Initialization
      • maxi starts at negative infinity so that the right-most element is always a leader.
    2. Backward Scan
      • At each position i, compare arr[i] with maxi.
      • If arr[i] is ≥ maxi, no larger element exists to its right → it’s a leader.
      • Push it into result and update maxi.
    3. Result Reversal
      • Leaders were gathered right-to-left; a single reverse() restores left-to-right order.

    Dry Run (Input [16, 17, 4, 3, 5, 2])

    i (index)arr[i]maxi (before)arr[i] ≥ maxi?result (after)maxi (after)
    52-∞✅[2]2
    452✅[2, 5]5
    335❌[2, 5]5
    245❌[2, 5]5
    1175✅[2, 5, 17]17
    01617❌[2, 5, 17]17

    After reversal → [17, 5, 2], which matches the expected leaders.

    Time & Space Complexity

    • Time: O(n) – single traversal of the array.
    • Space: O(1) extra (the result list holds at most n leaders, but no auxiliary arrays proportional to n are created aside from output).

    Precise: O(n) for scanning + O(n) in worst-case leaders list → effectively still O(n) total.

    Conclusion

    The right-to-left scan leverages a running maximum to identify leaders in just one pass. This elegant approach highlights a common pattern in array problems: processing from the end can turn seemingly quadratic checks into linear-time solutions. Master it and similar “suffix maximum” tricks will feel natural in future challenges!

    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Array Medium
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleMajority Element | Leetcode 169 | Explained in Python
    Next Article Majority Element II | Leetcode 229 | Explained in Python
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (4)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    Confusion Matrix in Machine Learning: An Interactive Guide

    21 October 2026

    100 SQL Interview Questions with Queries and Answers (Freshers to Experienced)

    17 October 2026

    Logistic Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    Linear Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    100 Python Interview Questions and Answers for Freshers and Experienced (Free PDF)

    17 October 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.