Reading history

Leaders in an Array: O(n) Right-to-Left Solution

9 min read 2 views

An element is a leader if it is greater than everything to its right. Find all leaders in O(n) by scanning from the right, with C code and output.

An element is a leader when nothing to its right is bigger. Scanning from right to left while tracking the maximum finds every leader in a single pass.


What Makes an Element a Leader

What is a Leader?

A leader is an element that is greater than or equal to all elements to its right side. The rightmost element has no elements to its right, so it’s always a leader.

Example:

Array: [16, 17, 4, 3, 5, 2]
Leaders: 17, 5, 2

Explanation:

  • 17 is greater than all elements to its right (4, 3, 5, 2).
  • 5 is greater than all elements to its right (2).
  • 2 has no elements to its right, so it’s a leader.

Why This Problem Matters

  • Efficient traversal: Right-to-left scanning pattern.
  • Algorithm optimization: From O(n²) to O(n).
  • Interview preparation: Common coding question.
  • Pattern recognition: Identify superior elements.

Approaches

ApproachTime ComplexitySpace Complexity
Naive (Nested Loops)O(n²)O(1)
Suffix MaximumO(n)O(1) auxiliary

From Nested Loops to One Right-to-Left Scan

Naive Approach: O(n²)

Use nested loops to compare each element with all elements to its right.

#include <stdio.h>
#include <stdlib.h>

/* Naive approach: O(n²) */
int *leadersNaive(int arr[], int n, int *resultSize) {
    int *result = malloc(n * sizeof(int));
    if (result == NULL) return NULL;

    int count = 0;

    for (int i = 0; i < n; i++) {
        int j;

        /* Check if any larger element to the right */
        for (j = i + 1; j < n; j++) {
            if (arr[i] < arr[j]) {
                break;   // arr[i] is not a leader
            }
        }

        /* If no larger element found, it's a leader */
        if (j == n) {
            result[count++] = arr[i];
        }
    }

    *resultSize = count;
    return result;
}

int main(void) {
    int arr[] = {16, 17, 4, 3, 5, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    int resultSize;

    int *result = leadersNaive(arr, n, &resultSize);

    printf("Leaders (naive): ");
    for (int i = 0; i < resultSize; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    free(result);
    return 0;
}

Expected output:

Leaders (naive): 17 5 2

Optimal Approach: O(n) Using Suffix Maximum

Scan from right to left, tracking the maximum seen so far.

#include <stdio.h>
#include <stdlib.h>

/* Optimal approach: O(n) */
int *leadersOptimal(int arr[], int n, int *resultSize) {
    int *result = malloc(n * sizeof(int));
    if (result == NULL) return NULL;

    int count = 0;

    /* Rightmost element is always a leader */
    int maxRight = arr[n - 1];
    result[count++] = maxRight;

    /* Traverse from right to left */
    for (int i = n - 2; i >= 0; i--) {
        if (arr[i] >= maxRight) {
            maxRight = arr[i];
            result[count++] = maxRight;
        }
    }

    /* Reverse the result */
    for (int i = 0; i < count / 2; i++) {
        int temp = result[i];
        result[i] = result[count - i - 1];
        result[count - i - 1] = temp;
    }

    *resultSize = count;
    return result;
}

int main(void) {
    int arr[] = {16, 17, 4, 3, 5, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    int resultSize;

    int *result = leadersOptimal(arr, n, &resultSize);

    printf("Leaders (optimal): ");
    for (int i = 0; i < resultSize; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    free(result);
    return 0;
}

Expected output:

Leaders (optimal): 17 5 2

Step-by-Step Illustration

arr[] = {16, 17, 4, 3, 5, 2}

Initially: maxRight = 2, result = {2}

i=4: arr[4]=5 >= 2 → maxRight=5, result={2,5}
i=3: arr[3]=3 < 5 → no change
i=2: arr[2]=4 < 5 → no change
i=1: arr[1]=17 >= 5 → maxRight=17, result={2,5,17}
i=0: arr[0]=16 < 17 → no change

Reverse result: {17, 5, 2}

Leaders Program in C

This program demonstrates both approaches with comprehensive examples and edge cases.

Program: Leaders in Array Finder

/**
 * leaders_in_array.c
 * Demonstrates finding leaders using naive and optimal approaches.
 * Includes edge cases and performance comparison.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>

#define MAX_LINE_LEN 100

/* Function prototypes */
int *findLeadersNaive(const int arr[], int n, int *resultSize);
int *findLeadersOptimal(const int arr[], int n, int *resultSize);
void demonstrateNaive(void);
void demonstrateOptimal(void);
void demonstrateEdgeCases(void);
void demonstratePerformance(void);
void printArray(const int arr[], int n);

int main(void) {
    int choice;
    char buffer[MAX_LINE_LEN];

    printf("=== Leaders in Array ===\n");

    while (1) {
        printf("\n--- Menu ---\n");
        printf("1. Naive Approach O(n²)\n");
        printf("2. Optimal Approach O(n)\n");
        printf("3. Edge Cases\n");
        printf("4. Performance Comparison\n");
        printf("5. Exit\n");
        printf("Enter choice: ");
        fflush(stdout);

        if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
            fprintf(stderr, "Error reading choice.\n");
            return EXIT_FAILURE;
        }

        choice = atoi(buffer);

        switch (choice) {
            case 1:
                demonstrateNaive();
                break;
            case 2:
                demonstrateOptimal();
                break;
            case 3:
                demonstrateEdgeCases();
                break;
            case 4:
                demonstratePerformance();
                break;
            case 5:
                printf("Exiting.\n");
                return EXIT_SUCCESS;
            default:
                printf("Invalid choice. Please try again.\n");
                break;
        }
    }

    return EXIT_SUCCESS;
}

/* Naive approach: O(n²) */
int *findLeadersNaive(const int arr[], int n, int *resultSize) {
    int *result = malloc(n * sizeof(int));
    if (result == NULL) {
        *resultSize = 0;
        return NULL;
    }

    int count = 0;

    for (int i = 0; i < n; i++) {
        int j;

        for (j = i + 1; j < n; j++) {
            if (arr[i] < arr[j]) {
                break;
            }
        }

        if (j == n) {
            result[count++] = arr[i];
        }
    }

    *resultSize = count;
    return result;
}

/* Optimal approach: O(n) */
int *findLeadersOptimal(const int arr[], int n, int *resultSize) {
    int *result = malloc(n * sizeof(int));
    if (result == NULL) {
        *resultSize = 0;
        return NULL;
    }

    int count = 0;
    int maxRight = arr[n - 1];
    result[count++] = maxRight;

    for (int i = n - 2; i >= 0; i--) {
        if (arr[i] >= maxRight) {
            maxRight = arr[i];
            result[count++] = maxRight;
        }
    }

    /* Reverse */
    for (int i = 0; i < count / 2; i++) {
        int temp = result[i];
        result[i] = result[count - i - 1];
        result[count - i - 1] = temp;
    }

    *resultSize = count;
    return result;
}

/* Demonstrates naive approach */
void demonstrateNaive(void) {
    printf("\n=== Naive Approach O(n²) ===\n");

    int arr[] = {16, 17, 4, 3, 5, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    int resultSize;

    printf("Array: ");
    printArray(arr, n);

    int *result = findLeadersNaive(arr, n, &resultSize);

    printf("Leaders: ");
    for (int i = 0; i < resultSize; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    printf("Time: O(n²), Space: O(1) auxiliary\n");
    free(result);
}

/* Demonstrates optimal approach */
void demonstrateOptimal(void) {
    printf("\n=== Optimal Approach O(n) ===\n");

    int arr[] = {16, 17, 4, 3, 5, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    int resultSize;

    printf("Array: ");
    printArray(arr, n);

    int *result = findLeadersOptimal(arr, n, &resultSize);

    printf("Leaders: ");
    for (int i = 0; i < resultSize; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    printf("Time: O(n), Space: O(1) auxiliary\n");
    free(result);
}

/* Demonstrates edge cases */
void demonstrateEdgeCases(void) {
    printf("\n=== Edge Cases ===\n");

    /* Case 1: Empty array */
    int emptyArr[] = {};
    int emptyN = 0;
    printf("Empty array: ");
    if (emptyN > 0) {
        int size;
        int *result = findLeadersOptimal(emptyArr, emptyN, &size);
        for (int i = 0; i < size; i++) printf("%d ", result[i]);
        free(result);
    }
    printf("(no elements)\n");

    /* Case 2: Single element */
    int singleArr[] = {42};
    int singleN = sizeof(singleArr) / sizeof(singleArr[0]);
    int size;
    int *result = findLeadersOptimal(singleArr, singleN, &size);
    printf("Single element: ");
    for (int i = 0; i < size; i++) printf("%d ", result[i]);
    printf("\n");
    free(result);

    /* Case 3: All same elements */
    int sameArr[] = {5, 5, 5, 5, 5};
    int sameN = sizeof(sameArr) / sizeof(sameArr[0]);
    result = findLeadersOptimal(sameArr, sameN, &size);
    printf("All same elements: ");
    for (int i = 0; i < size; i++) printf("%d ", result[i]);
    printf("\n");
    free(result);

    /* Case 4: Increasing order */
    int incArr[] = {1, 2, 3, 4, 5};
    int incN = sizeof(incArr) / sizeof(incArr[0]);
    result = findLeadersOptimal(incArr, incN, &size);
    printf("Increasing order: ");
    for (int i = 0; i < size; i++) printf("%d ", result[i]);
    printf("\n");
    free(result);

    /* Case 5: Decreasing order */
    int decArr[] = {5, 4, 3, 2, 1};
    int decN = sizeof(decArr) / sizeof(decArr[0]);
    result = findLeadersOptimal(decArr, decN, &size);
    printf("Decreasing order: ");
    for (int i = 0; i < size; i++) printf("%d ", result[i]);
    printf("\n");
    free(result);

    /* Case 6: Negative numbers */
    int negArr[] = {-5, -2, -8, -1, -4};
    int negN = sizeof(negArr) / sizeof(negArr[0]);
    result = findLeadersOptimal(negArr, negN, &size);
    printf("Negative numbers: ");
    for (int i = 0; i < size; i++) printf("%d ", result[i]);
    printf("\n");
    free(result);
}

/* Demonstrates performance */
void demonstratePerformance(void) {
    printf("\n=== Performance Comparison ===\n");

    int n = 10000;
    int *arr = malloc(n * sizeof(int));

    if (arr == NULL) {
        perror("malloc failed");
        return;
    }

    /* Fill with random-like values */
    for (int i = 0; i < n; i++) {
        arr[i] = (i * 7) % 100;
    }

    int resultSize;

    /* Naive */
    clock_t start = clock();
    int *resultNaive = findLeadersNaive(arr, n, &resultSize);
    clock_t end = clock();
    double naiveTime = ((double)(end - start)) / CLOCKS_PER_SEC * 1000;
    free(resultNaive);

    /* Optimal */
    start = clock();
    int *resultOptimal = findLeadersOptimal(arr, n, &resultSize);
    end = clock();
    double optimalTime = ((double)(end - start)) / CLOCKS_PER_SEC * 1000;
    free(resultOptimal);

    printf("Array size: %d\n", n);
    printf("Naive O(n²): %.3f ms\n", naiveTime);
    printf("Optimal O(n): %.3f ms\n", optimalTime);

    free(arr);
}

/* Prints array */
void printArray(const int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

Explanation of Approaches

  1. Naive: For each element, check all elements to the right.
  2. Optimal: Scan from right, track maximum, reverse result.
  3. Edge cases: Empty, single, all same, increasing, decreasing, negative.
  4. Performance: Optimal is significantly faster for large arrays.

Expected Output (partial)

=== Leaders in Array ===

--- Menu ---
1. Naive Approach O(n²)
2. Optimal Approach O(n)
3. Edge Cases
4. Performance Comparison
5. Exit
Enter choice: 2

=== Optimal Approach O(n) ===
Array: 16 17 4 3 5 2
Leaders: 17 5 2
Time: O(n), Space: O(1) auxiliary

--- Menu ---
...
Enter choice: 3

=== Edge Cases ===
Empty array: (no elements)
Single element: 42
All same elements: 5 5 5 5 5
Increasing order: 5
Decreasing order: 5 4 3 2 1
Negative numbers: -1 -4

--- Menu ---
...
Enter choice: 4

=== Performance Comparison ===
Array size: 10000
Naive O(n²): 45.678 ms
Optimal O(n): 0.234 ms

Equal Values and Output Order

1. Not Handling Empty Array

Accessing arr[n-1] on empty array is undefined.

Solution: Check n > 0 before accessing elements.

2. Using > Instead of >=

Leaders include elements equal to the maximum on the right.

if (arr[i] > maxRight)   // BUG: misses equal elements
if (arr[i] >= maxRight)  // Correct

3. Forgetting to Reverse Result

Right-to-left scan produces reversed order.

Solution: Reverse the result before returning.

4. Memory Leaks

Forgetting to free allocated result arrays.

Solution: Always free allocated memory.

5. Not Checking malloc Return

malloc can return NULL.

Solution: Check allocation return values.

6. Wrong Index in Right-to-Left Loop

Starting from n instead of n-2 after initializing with arr[n-1].

Solution: Start from n - 2.

7. All Elements Same

Every element is a leader.

Solution: Use >= to include equal elements.

8. Integer Overflow in Indices

Large arrays overflow int.

Solution: Use size_t for indices.

9. Not Validating Input

Invalid input causes crashes.

Solution: Validate user input.

10. Memory Considerations

  • Naive: O(1) auxiliary space.
  • Optimal: O(1) auxiliary space (result array not counted as auxiliary).
  • Both allocate O(n) for result.
  • No recursion, so no stack space issues.

Leaders in an Array Summary

Finding leaders in an array demonstrates efficient right-to-left traversal. The optimal O(n) approach using suffix maximum is significantly faster than the naive O(n²) approach.

Key Takeaways

  • Leader: element >= all elements to its right.
  • Rightmost element is always a leader.
  • Naive: O(n²) with nested loops.
  • Optimal: O(n) with right-to-left scan.
  • Use >= for equal elements.
  • Reverse result after right-to-left scan.

Best Practices

  1. Use optimal O(n) approach.
  2. Use >= for leader comparison.
  3. Handle empty arrays.
  4. Check malloc return values.
  5. Free allocated memory.
  6. Reverse result correctly.
  7. Test with edge cases.
  8. Use const for read-only arrays.
  9. Document complexity.
  10. Profile performance for large arrays.

By mastering this problem, you’ll develop efficient array traversal skills applicable to many algorithmic challenges.

Lessons are also marked complete when you click Next.