![]() |
VOOZH | about |
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 11Input : 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 :
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:
10 6 12 5 12 11 10
Time Complexity:
Therefore, the overall time complexity of the algorithm is O(n*log(n)).
Auxiliary Space:
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.