Skip to content
Related Articles
Closest greater or same value on left side for every element in array
• Difficulty Level : Basic
• Last Updated : 26 May, 2021

Given an array of integers, find the closest (not considering the distance, but value) greater or the same value on the left of every element. If an element has no greater or same value on the left side, print -1.

Examples:

Input : arr[] = {10, 5, 11, 6, 20, 12}
Output : -1, 10, -1, 10, -1, 20
The first element has nothing on the left side, so the answer for first is -1.
Second, element 5 has 10 on the left, so the answer is 10.
Third element 11 has nothing greater or the same, so the answer is -1.
Fourth element 6 has 10 as value wise closes, so the answer is 10
Similarly, we get values for the fifth and sixth elements.

A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse toward the left of it and find the closest (value-wise) greater element. The time complexity of this solution is O(n*n)

An efficient solution is to use Self-Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest greater operations in O(Log n) time.
We use lower_bound() in C++ to find the closest greater element. This function works in Log n time for a set.

## C++

 `// C++ implementation of efficient algorithm to find``// greater or same element on left side``#include ``#include ``using` `namespace` `std;` `// Prints greater elements on left side of every element``void` `printPrevGreater(``int` `arr[], ``int` `n)``{``    ``set<``int``> s;``    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// First search in set``        ``auto` `it = s.lower_bound(arr[i]);``        ``if` `(it == s.end()) ``// If no greater found``            ``cout << ``"-1"``                 ``<< ``" "``;``        ``else``            ``cout << *it << ``" "``;` `        ``// Then insert``        ``s.insert(arr[i]);``    ``}``}` `/* Driver program to test insertion sort */``int` `main()``{``    ``int` `arr[] = { 10, 5, 11, 10, 20, 12 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``printPrevGreater(arr, n);``    ``return` `0;``}`

## Java

 `// Java implementation of efficient algorithm``// to find greater or same element on left side``import` `java.util.TreeSet;` `class` `GFG {` `    ``// Prints greater elements on left side``    ``// of every element``    ``static` `void` `printPrevGreater(``int``[] arr, ``int` `n)``    ``{``        ``TreeSet ts = ``new` `TreeSet<>();``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``Integer c = ts.ceiling(arr[i]);``            ``if` `(c == ``null``) ``// If no greater found``                ``System.out.print(-``1` `+ ``" "``);``            ``else``                ``System.out.print(c + ``" "``);` `            ``// Then insert``            ``ts.add(arr[i]);``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int``[] arr = { ``10``, ``5``, ``11``, ``10``, ``20``, ``12` `};``        ``int` `n = arr.length;``        ``printPrevGreater(arr, n);``    ``}``}` `// This code is contributed by``// sanjeev2552`

## Python3

 `# Python3 implementation of efficient algorithm``# to find greater or same element on left side` `# Prints greater elements``# on left side of every element``def` `printPrevGreater(arr, n):` `    ``s ``=` `set``()``    ``for` `i ``in` `range``(``0``, n):` `        ``# First search in set``        ``it ``=` `[x ``for` `x ``in` `s ``if` `x >``=` `arr[i]]``        ``if` `len``(it) ``=``=` `0``: ``# If no greater found``            ``print``(``"-1"``, end ``=` `" "``)``        ``else``:                ``            ``print``(``min``(it), end ``=` `" "``)        ` `        ``# Then insert``        ``s.add(arr[i])` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[``10``, ``5``, ``11``, ``10``, ``20``, ``12``]``    ``n ``=` `len``(arr)``    ``printPrevGreater(arr, n)``    ` `# This code is contributed by Rituraj Jain`

## C#

 `// C# implementation of efficient algorithm``// to find greater or same element on left side``using` `System;``using` `System.Collections.Generic;` `class` `GFG {` `    ``// To get the minimum value``    ``static` `int` `minimum(SortedSet<``int``> ss)``    ``{``        ``int` `min = ``int``.MaxValue;` `        ``foreach``(``int` `i ``in` `ss) ``if` `(i < min)``            ``min = i;` `        ``return` `min;``    ``}` `    ``// Prints greater elements on left side``    ``// of every element``    ``static` `void` `printPrevGreater(``int``[] arr, ``int` `n)``    ``{``        ``SortedSet<``int``> s = ``new` `SortedSet<``int``>();` `        ``for` `(``int` `i = 0; i < n; i++) {``            ``SortedSet<``int``> ss = ``new` `SortedSet<``int``>();` `            ``// First search in set``            ``foreach``(``int` `x ``in` `s) ``if` `(x >= arr[i])``                ``ss.Add(x);` `            ``if` `(ss.Count == 0) ``// If no greater found``                ``Console.Write(-1 + ``" "``);``            ``else``                ``Console.Write(minimum(ss) + ``" "``);` `            ``// Then insert``            ``s.Add(arr[i]);``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int``[] arr = { 10, 5, 11, 10, 20, 12 };``        ``int` `n = arr.Length;``        ``printPrevGreater(arr, n);``    ``}``}` `// This code is contributed by PrinciRaj1992`

## Javascript

 ``
Output:
`-1 10 -1 10 -1 20`

Time Complexity: O(n Log 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 industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up