VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-closest-value-for-every-element-in-array/

⇱ Find closest value for every element in array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find closest value for every element in array

Last Updated : 11 Jul, 2025

Given an array of integers, find the closest element for every element. 

Examples:

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

Input : arr[] = {10, 5, 11, 10, 20, 12} 
Output : 10 10 12 10 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 the remaining array and find the closest element. The time complexity of this solution is  O(N2).

Steps:

1. Create a base case in which if the size of the 
 ‘vec’ array is one print -1;
2.create a nested iterations using the ‘for’ loop with the help of 
‘i’ and ‘j’ variables.
3. Take two variables to store the abs() difference and closest
 element for an element. 
4. In the second ‘for’ loop, assign the value at the ‘jth’
 position of the ‘vec’ vector, if that element is close to 
 the respective element.
5.Print the closest element.

Implementation of above approach :


Output
vec Array:- 10 5 11 6 20 12 10 
Resultant Array:- 10 6 10 5 12 11 10 
Time Complexity: O(N2)
Auxiliary Space: O(1)

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. 

Implementation:

Output:
10 6 12 5 12 11 10

Time Complexity: 

  • The first loop for inserting all the elements into the TreeMap takes O(nlog(n)) time because TreeMap uses a Red-Black tree internally to store the elements, and insertion takes O(log(n)) time in the average case, and since there are 'n' elements in the array, the total time complexity for inserting all elements into the TreeMap is O(nlog(n)).
  • The second loop for finding the smallest greater element for each array element takes O(nlog(n)) time because the TreeMap provides the higherKey() and lowerKey() methods that take O(log(n)) time in the average case to find the keys greater than and less than the given key, respectively. Since we are calling these methods 'n' times, the total time complexity for finding the smallest greater element for each array element is O(nlog(n)).

Therefore, the overall time complexity of the algorithm is O(n*log(n)).

Auxiliary Space:

  • The algorithm uses a TreeMap to store the array elements, which takes O(n) space because each element takes O(1) space, and there are 'n' elements in the array.
  • Therefore, the overall auxiliary space complexity of the algorithm is O(n).

Exercise: Another efficient solution is to use sorting that also works in O(n Log n) time. Write complete algorithm and code for sorting based solution.

Comment
Article Tags:
Article Tags: