CoCubes Programming Question – 1

Printing all the Leaders in an Array

Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side.

And the rightmost element is always a leader. For example int the array {16, 19, 4, 3, 8, 3}, leaders are 19, 8 and 3?

 

58 comments on “CoCubes Programming Question – 1”


  • Ritu

    #include
    using namespace std;

    void findLeaders(int arr[],int len){

    int leaders[]={};
    for(int i=0;i<len;i++){
    int flag=0;
    // cout<<"\n a[i]: "<<arr[i];
    for(int j=i+1;j<len;j++){
    //cout<<"\t \t a[j]: "<<arr[j];
    if(arr[i]<arr[j]){
    flag=1;
    break;
    }
    }

    if(flag==0)
    cout<<" | "<<arr[i];
    }
    }

    int main() {
    // // Write C++ code here
    // int arr[]={16, 19, 4, 3, 8, 3};
    // //leaders: 19, 8 and 3?
    // int len=sizeof(arr)/sizeof(arr[0]);
    // cout<<"\nlength: "<<len;
    // findLeaders(arr,len);
    int len;
    cout<>len;
    int arr[len];
    cout<<"\n Enter Array Elements: ";
    for(int i=0;i>arr[i];
    cout<<"\n Leader Array: ";
    findLeaders(arr,len);

    return 0;
    }


  • Tushar

    Time comp: O(n)
    Python 3

    ip = list(map(int,input().split()))
    leaders = []
    max = ip[-1]
    for i in ip[::-1]:
    If i > max:
    leaders.insert(0,i)
    max = i
    leaders.append(ip[-1])
    print(leaders)


    • 20R21A12C6

      import java.util.*;
      public class Main
      {
      public static void main(String[] args)
      {
      Scanner s = new Scanner(System.in);
      LinkedHashSet l =new LinkedHashSet();
      int n =s.nextInt();
      int ar[] = new int[n];
      for(int i =0;i0;i–)
      {
      if(ar[i]>max)
      {
      l.add(ar[i]);
      max=ar[i];
      }
      }
      System.out.println(l);
      }
      }