Related Articles

# Print greater elements present on the left side of each array element

• Difficulty Level : Easy
• Last Updated : 13 Jul, 2021

Given an array arr[] consisting of N distinct integers, the task is to print for each array element, all the greater elements present on its left.

Examples:

Input: arr[] = {5, 3, 9, 0, 16, 12}
Output:
5:
3: 5
9:
0: 9 5 3
16:
12: 16

Input: arr[] = {1, 2, 0}
Output:
1:
2:
0: 2 1

Naive Approach: The simplest approach to solve the problem is to traverse the array and for each array element, traverse all its preceding elements and print the ones that are greater than the current element.

## C++

 `// C++ program for Naive approach``#include ``using` `namespace` `std;` `// Function to print all greater elements on the left of each array element``void` `printGreater(vector<``int``>& arr)``{``    ``// store the size of array in variable n``    ``int` `n = arr.size();``    ``for` `(``int` `i = 0; i < n; i++)``    ``{``        ``// result is used to store elements which are greater than current element present left side of current element``        ``vector<``int``> result;` `        ``// traversing all the elements which are left of current element arr[i]``      ` `        ``for` `(``int` `j = i - 1; j >= 0; j--)``        ``{``            ``//checking whether arr[j] (left element) is greater than current element or not``            ``// if yes then insert the element to the result vector``            ``if` `(arr[j] > arr[i])``            ``{``                ``result.push_back(arr[j]);``            ``}``        ``}``        ``cout << arr[i] << ``": "``;``      ` `        ``//printing all the elements present in result vector``        ``for` `(``int` `k = 0; k < result.size(); k++)``        ``{``            ``cout << result[k] << ``" "``;``        ``}``        ``cout << endl;``    ``}``}` `//Driver Code``int` `main()``{``    ``vector<``int``> arr{5, 3, 9, 0, 16, 12};``    ``printGreater(arr);``    ``return` `0;``}`

## Java

 `// java program for Naive approach``import` `java.util.*;` `class` `GFG{` `  ``// Function to print all greater elements on the left of each array element``  ``static` `void` `printGreater(ArrayList arr)``  ``{``    ``// store the size of array in variable n``    ``int` `n = arr.size();``    ``for` `(``int` `i = ``0``; i < n; i++)``    ``{``      ` `      ``// result is used to store elements which``      ``// are greater than current element present``      ``// left side of current element``      ``ArrayList result``        ``= ``new` `ArrayList();` `      ``// traversing all the elements which``      ``// are left of current element arr[i]` `      ``for` `(``int` `j = i - ``1``; j >= ``0``; j--)``      ``{``        ``// checking whether arr[j] (left element) is``        ``// greater than current element or not``        ``// if yes then insert the element to the result vector``        ``if` `(arr.get(j) > arr.get(i))``        ``{``          ``result.add(arr.get(j));``        ``}``      ``}``      ``System.out.print(arr.get(i) + ``": "``);` `      ``// printing all the elements present in result vector``      ``for` `(``int` `k = ``0``; k < result.size(); k++)``      ``{``        ``System.out.print(result.get(k) +``" "``);``      ``}``      ``System.out.println();``    ``}``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String args[])``  ``{``    ``ArrayList arr = ``new` `ArrayList(Arrays.asList(``5``, ``3``, ``9``, ``0``, ``16``, ``12``));``    ``printGreater(arr);``  ``}``}` `// This code is contributed by bgangwar59.`

## Python3

 `# Python3 program for Naive approach` `# Function to print all greater``# elements on the left of each``# array element``def` `printGreater(arr):``    ` `    ``# Store the size of array``    ``# in variable n``    ``n ``=` `len``(arr)``    ` `    ``for` `i ``in` `range``(n):``        ` `        ``# Result is used to store elements``        ``# which are greater than current``        ``# element present left side of``        ``# current element``        ``result ``=` `[]` `        ``# Traversing all the elements``        ``# which are left of current``        ``# element arr[i]``        ``j ``=` `i ``-` `1``        ` `        ``while``(j >``=` `0``):``            ` `            ``# Checking whether arr[j] (left element)``            ``# is greater than current element or not``            ``# if yes then insert the element to the``            ``# result vector``            ``if` `(arr[j] > arr[i]):``                ``result.append(arr[j])``                ` `            ``j ``-``=` `1``            ` `        ``print``(arr[i], end ``=` `": "``)``      ` `        ``# Printing all the elements present``        ``# in result vector``        ``for` `k ``in` `range``(``len``(result)):``            ``print``(result[k], end ``=` `" "``)``            ` `        ``print``(``"\n"``, end ``=` `"")` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``arr ``=` `[ ``5``, ``3``, ``9``, ``0``, ``16``, ``12` `]``    ` `    ``printGreater(arr)` `# This code is contributed by ipg2016107`

## C#

 `// C# program for Naive approach``using` `System;``using` `System.Collections.Generic;``class` `GFG``{``  ` `    ``// Function to print all greater elements on the left of``    ``// each array element``    ``static` `void` `printGreater(``int``[] arr)``    ``{``      ` `        ``// store the size of array in variable n``        ``int` `n = arr.Length;``        ``for` `(``int` `i = 0; i < n; i++)``        ``{``          ` `            ``// result is used to store elements which are``            ``// greater than current element present left``            ``// side of current element``            ``List<``int``> result = ``new` `List<``int``>();` `            ``// traversing all the elements which are left of``            ``// current element arr[i]` `            ``for` `(``int` `j = i - 1; j >= 0; j--)``            ``{``              ` `                ``// checking whether arr[j] (left element) is``                ``// greater than current element or not``                ``// if yes then insert the element to the``                ``// result vector``                ``if` `(arr[j] > arr[i]) {``                    ``result.Add(arr[j]);``                ``}``            ``}``            ``Console.Write(arr[i] + ``": "``);` `            ``// printing all the elements present in result``            ``// vector``            ``for` `(``int` `k = 0; k < result.Count; k++) {``                ``Console.Write(result[k] + ``" "``);``            ``}``            ``Console.WriteLine();``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``int``[] arr = { 5, 3, 9, 0, 16, 12 };``        ``printGreater(arr);``    ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``
Output
```5:
3: 5
9:
0: 9 3 5
16:
12: 16 ```

Time Complexity: O(N2)
Auxiliary Space: O(N)

Efficient Approach: To optimize the above approach, the idea is to make use of a self-balancing Binary Search Trees. Set in C++ is implemented using self-balancing BSTs and can be used to solve this problem. Follow the steps to solve the problem:

Below is the implementation of the above approach:

## C++

 `// C++ Program for the above approach``#include ``using` `namespace` `std;` `// Function to print all greater elements``// on the left of each array element``void` `printGreater(vector<``int``>& arr)``{``    ``int` `n = arr.size();` `    ``// Set to implement``    ``// self-balancing BSTs``    ``set<``int``, greater<``int``> > s;` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// Insert the current``        ``// element into the set``        ``auto` `p = s.insert(arr[i]);``        ``auto` `j = s.begin();` `        ``cout << arr[i] << ``": "``;` `        ``// Iterate through the set``        ``while` `(j != p.first) {` `            ``// Print the element``            ``cout << *j << ``" "``;``            ``j++;``        ``}``        ``cout << endl;``    ``}``}` `// Driver Code``int` `main()``{``    ``vector<``int``> arr{ 5, 3, 9, 0, 16, 12 };``    ``printGreater(arr);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;``import` `java.lang.*;``import` `java.util.*;` `class` `GFG{` `// Function to print all greater elements``// on the left of each array element``static` `void` `printGreater(``int` `arr[])``{``    ``int` `n = arr.length;` `    ``// Set to implement``    ``// self-balancing BSTs``    ``TreeSet s = ``new` `TreeSet<>(``        ``Collections.reverseOrder());` `    ``// Traverse the array``    ``for``(``int` `i = ``0``; i < n; i++)``    ``{``        ` `        ``// Insert the current``        ``// element into the set``        ``s.add(arr[i]);` `        ``System.out.print(arr[i] + ``": "``);` `        ``// Iterate through the set``        ``for``(``int` `v : s)``        ``{``            ``if` `(v == arr[i])``                ``break``;` `            ``// Print the element``            ``System.out.print(v + ``" "``);``        ``}``        ``System.out.println();``    ``}``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``5``, ``3``, ``9``, ``0``, ``16``, ``12` `};``    ``printGreater(arr);``}``}` `// This code is contributed by Kingash`

## Javascript

 ``
Output
```5:
3: 5
9:
0: 9 5 3
16:
12: 16 ```

Time Complexity: O(N2)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up