VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-closest-number-array/

⇱ Find closest number in Sorted array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find closest number in Sorted array

Last Updated : 7 Jan, 2025

Given an array arr[] of sorted integers of size n. We need to find the closest value to the given number k. Array may contain duplicate values and negative numbers. If the smallest difference with k is the same for two values in the array return the greater value.

Examples:

Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}, target = 11
Output : 9
Explanation : 9 is closest to 11 in given array

Input :arr[] = {2, 5, 6, 7, 8, 8, 9}, target = 4
Output : 5
Explanation :5 is closest to 4 in given array

Input :arr[] = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32}, target = 17
Output : 19
Explanation : 15 and 19 both are closest to 17 in given array ,so return max(15, 19) which is 19

[Naive Approach] - Theta(n) Time and O(1) Space

The idea is to go through the given array and check how close each element is to the target value by comparing their differences. We keeps track of the element that is closest to the target. At first, the result is set to the first element of the array, and with each loop, we updates the result if we finds a closer element.


Output
19

Time Complexity : O(n), where n is size of arr[]
Space Complexity : O(1)

[Better Approach] - O(n) Time and O(1) Space

The idea is to go through the array until we finds the first element that is greater than or equal to the target. If no such element is found, meaning all elements are smaller, we return the lastelement of the array. If we finds such an element, we checks which one is closer to the target by comparing it with the previous element. We then returns the element that is closest to the target.


Output
19

Time Complexity : O(n), where n is size of arr[]
Space Complexity : O(1)

[Expected Approach] Binary Search - O(Log n) Time and O(1) Space

The approach is to use binary search to find the element in a sorted array that is closest to the target value. We start by setting the result to the first element. Then, using two pointers lo and hi, we repeatedly narrow down the search space until we find the closest element. At each step, we compare the middle element mid with the target. If it's closer than the current result, we update result. If there's a tie, the larger value is chosen. If we find the exact target, we return it right away. Otherwise, the search continues, and the closest value is returned at the end.


Output
9

Time Complexity : O(Log n), due to binary search, where n is size of arr[]
Space Complexity : O(1)


Comment