# Find closest greater value for every element in array

Given an array of integers, find the closest greater element for every element. If there is no greater element then print -1

Examples:

Input : arr[] = {10, 5, 11, 6, 20, 12}
Output : 11 6 12 10 -1 20

Input : arr[] = {10, 5, 11, 10, 20, 12}
Output : 11 10 12 11 -1 20

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest greater element. Time complexity of this solution is O(n*n)

A better solution is to use sorting. We sort all elements, then for every element, traverse toward right until we find a greater element (Note that there can be multiple occurrences of an element).

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.

 `// Java program to find closest greater value for ` `// every array element ` `import` `java.util.*; ` ` `  `class` `TreeSetDemo { ` `    ``public` `static` `void` `closestGreater(``int``[] arr) ` `    ``{ ` `        ``// Insert all array elements into a TreeSet ` `        ``TreeSet ts = ``new` `TreeSet(); ` `        ``for` `(``int` `i = ``0``; i < arr.length; i++) ` `            ``ts.add(arr[i]); ` ` `  `        ``// Find smallest greater element for every ` `        ``// array element ` `        ``for` `(``int` `i = ``0``; i < arr.length; i++) { ` `            ``Integer greater = ts.higher(arr[i]); ` `            ``if` `(greater == ``null``) ` `                ``System.out.print(-``1` `+ ``" "``); ` `            ``else` `                ``System.out.print(greater + ``" "``); ` `        ``} ` `    ``} ` ` `  `    ``public` `static` `void` `main(String[] args) ` `    ``{ ` `        ``int``[] arr = { ``10``, ``5``, ``11``, ``10``, ``20``, ``12``}; ` `        ``closestGreater(arr); ` `    ``} ` `} `

Output:

```11 10 12 11 -1 20
```

Time Complexity : O(n Log n)

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.