Given a sorted integer array
An integer
-
|a - x| < |b - x| , or -
|a - x| == |b - x| anda < b
Output: [1,2,3,4]
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Output: [1,2,3,4]
Constraints:
1 <= k <= arr.length 1 <= arr.length <= 104 arr is sorted in ascending order.-104 <= arr[i] ,x <= 104
Contents
Solution 1 - Using sliding window technique, and binary search, lookup for window size of 'k' with closest elements to 'x'
The intution behind this solution is, since we want to find
In this approach, we are going to apply sliding window technique using two pointers
Implementation steps:
-
First, create two variables
left ,right that we will use to adjust the window, initializeleft =0 andright = arr.length - k , the reason we initializeright witharr.length -k is because, we are trying to find elementx using binary search, at the same time find the window of sizek closest elements, and if we moveleft pointer towards right all the way to theright pointer, then we will not havek elements left. So, since we needk elements from that position, we are leavingk elements on the right side. -
Next, run a
while loop untilleft andright pointer cross each other, and check the following:-
Since the array is sorted, we will be doing a binary search to find element
x , or a closer to that element, at the same time window window of sizek which is closer tox , so computemid = left + right / 2 -
Check how far is the
left pointer element tox thanright pointer element, ifx-arr[mid] > arr[mid+k] -x , then moveleft pointer tomid+1 - Otherwise, move
right pointer tomid (inclusive ofmid , in case of a tie, we want to consider smaller element)
-
Since the array is sorted, we will be doing a binary search to find element
-
Finally, return the window between
left andleft+k
Complexity Analysis:
Time complexity: Above code runs in O(n) time, where
Space complexity: O(1).
Above implementations source code can be found at