Find closest smaller value for every element in array
Given an array of integers, find the closest smaller element for every element. If there is no smaller element then print -1
Examples:
Input : arr[] = {10, 5, 11, 6, 20, 12}
Output : 6, -1, 10, 5, 12, 11Input : arr[] = {10, 5, 11, 10, 20, 12}
Output : 5 -1 10 5 12 11
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 smaller 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 left until we find a smaller 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 smaller operations in O(Log n) time.
// Java program to find closest smaller value for // every array element import java.util.*; class TreeSetDemo { public static void closestSmaller(int[] arr) { // Insert all array elements into a TreeSet TreeSet<Integer> ts = new TreeSet<Integer>(); for (int i = 0; i < arr.length; i++) ts.add(arr[i]); // Find largest smaller element for every // array element for (int i = 0; i < arr.length; i++) { Integer smaller = ts.lower(arr[i]); if (smaller == null) System.out.print(-1 + " "); else System.out.print(smaller + " "); } } public static void main(String[] args) { int[] arr = { 10, 5, 11, 6, 20, 12 }; closestSmaller(arr); } } |
6 -1 10 5 12 11
Time Complexity : O(n Log n)
Recommended Posts:
- Find closest value for every element in array
- Find closest greater value for every element in array
- Closest greater element for every array element from another array
- Closest greater or same value on left side for every element in array
- Find the closest element in Binary Search Tree
- Find the element before which all the elements are smaller than it, and after which all are greater
- First strictly smaller element in a sorted array in Java
- Find the closest element in Binary Search Tree | Space Efficient Method
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Find the Sub-array with sum closest to 0
- Find closest number in array
- Find a triplet in an array whose sum is closest to a given number
- Find k closest numbers in an unsorted array
- Find next Smaller of next Greater in an array
- Find the nearest smaller numbers on left side in an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



