Given two arrays a and b, we need to build an array c such that every element c[i] of c contains a value from a which is greater than b[i] and is closest to b[i]. If a has no greater element than b[i], then value of c[i] is -1. All arrays are of same size.
Input : a = [ 2, 6, 5, 7, 0] b = [1, 3, 2, 5, 8] Output : c = [2, 5, 5, 7, -1] Input : a = [ 2, 6, 5, 7, 0] b = [0, 2, 3, 5, 1] Output : c = [2, 5, 5, 6, 2]
Naive Approach : For each element in b, we traverse the whole of a and try to find the closest greater element, and save the result for each search. This will cost time complexity of O(n^2).
Efficient Approach : Sort the array a, and for each b[i], apply binary search in sorted array a. For this method our time complexity will be O(nlogn).
Note: For closest greater element we can use upper_bound().
Below is the implementation.
Result = 5 2 1 6 5 -1
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.
- Closest greater or same value on left side for every element in array
- Find closest greater value for every element in array
- Find closest smaller value for every element in array
- Find closest value for every element in array
- Distance of closest zero to every element
- Maximum possible XOR of every element in an array with another array
- Replace every element with the least greater element on its right
- Rearrange an array such that every odd indexed element is greater than it previous
- Adding elements of an array until every element becomes greater than or equal to k
- Largest element smaller than current element on left for every element in Array
- Maximize sum of remaining elements after every removal of the array half with greater sum
- Find just strictly greater element from first array for each element in second array
- Length of longest subarray in which elements greater than K are more than elements not greater than K
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Permute two arrays such that sum of every pair is greater or equal to K
- Find the element that appears once in an array where every other element appears twice
- Find last element after deleting every second element in array of n integers
- Replace every array element by Bitwise Xor of previous and next element
- Replace every element of the array by its previous element
- Replace every element of the array by its next element
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Improved By : sanjeev2552