• edited by
30,831 views
81 81 votes

An element in an array $X$ is called a leader if it is greater than all elements to the right of it in $X$. The best algorithm to find all leaders in an array 

  1. solves it in linear time using a left to right pass of the array
  2. solves it in linear time using a right to left pass of the array
  3. solves it using divide and conquer in time $\Theta (n\log n)$
  4. solves it in time $\Theta( n^2)$

13 Answers

–1 –1 vote

Use two loops. The outer loop runs from 0 to size – 1 and one by one picks all elements from left to right. The inner loop compares the picked element to all the elements to its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader.

#include<iostream>

using namespace std;

/*C++ Function to print leaders in an array */

void printLeaders(int arr[], int size)

{

    for (int i = 0; i < size; i++)

    {

        int j;

        for (j = i+1; j < size; j++)

        {

            if (arr[i] <= arr[j])

                break;

        }   

        if (j == size) // the loop didn't break

            cout << arr[i] << " ";

  }

}

/* Driver program to test above function */

int main()

{

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

    int n = sizeof(arr)/sizeof(arr[0]);

    printLeaders(arr, n);

    return 0;

}

Answer:
Position:
Show:

Related questions

95 95 votes
14 answers 14 answers
50.3k
50.3k views
Rucha Shelke asked Sep 26, 2014
50,294 views
Given two arrays of numbers $a_{1},...,a_{n}$ and $b_{1},...,b_{n}$ where each number is $0$ or $1$, the fastest algorithm to find the largest span $(i, j)$ such that $ a...
106 106 votes
9 answers 9 answers
42.7k
42.7k views
Rucha Shelke asked Sep 17, 2014
42,660 views
Consider the following log sequence of two transactions on a bank account, with initial balance $12000,$ that transfer $2000$ to a mortgage payment and then apply a $5\%$...
57 57 votes
3 answers 3 answers
17.1k
17.1k views
Rucha Shelke asked Sep 26, 2014
17,149 views
Consider the following C-function in which $a[n]$ and $b[m]$ are two sorted integer arrays and $c[n+m]$ be another integer array,void xyz(int a[], int b [], int c []){ in...
25 25 votes
4 answers 4 answers
8.8k
8.8k views
Rucha Shelke asked Sep 26, 2014
8,823 views
A set $X$ can be represented by an array $x[n]$ as follows: $x\left [ i \right ]=\begin {cases} 1 & \text{if } i \in X \\ 0 & \text{otherwise} \end{cases}$Consider the ...