Open In App

C++ Program to Find closest number in array

Last Updated : 03 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. 

Examples:  

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

Input :arr[] = {2, 5, 6, 7, 8, 8, 9}; 
       Target number = 4
Output : 5

A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference.

An efficient solution is to use Binary Search.  

Output: 

9

Time Complexity: O(log(n))
Auxiliary Space: O(log(n)) (implicit stack is created due to recursion)

Approach 2: Using Two Pointers

Another approach to solve this problem is to use two pointers technique, where we maintain two pointers left and right, and move them towards each other based on their absolute difference with target.

Below are the steps:

  1. Initialize left = 0 and right = n-1, where n is the size of the array.
  2. Loop while left < right
    1. If the absolute difference between arr[left] and target is less than or equal to the absolute difference between arr[right] and target, move left pointer one step to the right, i.e. left++
    2. Else, move right pointer one step to the left, i.e. right–-
  3. Return arr[left], which will be the element closest to the target.

Below is the implementation of the above approach:


Output
9

Time Complexity: O(N), where n is the length of the array.
Auxiliary Space: O(1)

Please refer complete article on Find closest number in array for more details! 


Next Article

Similar Reads