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
5 is closest to 4 in given array
Input :arr[] = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
Target number = 34
Output : 32
32 is closest to 34 in given array
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 absolute difference.
An efficient solution is to use Binary Search.
C++
#include <bits/stdc++.h>
using namespace std;
int getClosest( int , int , int );
int findClosest( int arr[], int n, int target)
{
if (target <= arr[0])
return arr[0];
if (target >= arr[n - 1])
return arr[n - 1];
int i = 0, j = n, mid = 0;
while (i < j) {
mid = (i + j) / 2;
if (arr[mid] == target)
return arr[mid];
if (target < arr[mid]) {
if (mid > 0 && target > arr[mid - 1])
return getClosest(arr[mid - 1],
arr[mid], target);
j = mid;
}
else {
if (mid < n - 1 && target < arr[mid + 1])
return getClosest(arr[mid],
arr[mid + 1], target);
i = mid + 1;
}
}
return arr[mid];
}
int getClosest( int val1, int val2,
int target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
int main()
{
int arr[] = { 1, 2, 4, 5, 6, 6, 8, 8, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
int target = 11;
cout << (findClosest(arr, n, target));
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class FindClosestNumber {
public static int findClosest( int arr[], int target)
{
int n = arr.length;
if (target <= arr[ 0 ])
return arr[ 0 ];
if (target >= arr[n - 1 ])
return arr[n - 1 ];
int i = 0 , j = n, mid = 0 ;
while (i < j) {
mid = (i + j) / 2 ;
if (arr[mid] == target)
return arr[mid];
if (target < arr[mid]) {
if (mid > 0 && target > arr[mid - 1 ])
return getClosest(arr[mid - 1 ],
arr[mid], target);
j = mid;
}
else {
if (mid < n- 1 && target < arr[mid + 1 ])
return getClosest(arr[mid],
arr[mid + 1 ], target);
i = mid + 1 ;
}
}
return arr[mid];
}
public static int getClosest( int val1, int val2,
int target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 5 , 6 , 6 , 8 , 9 };
int target = 11 ;
System.out.println(findClosest(arr, target));
}
}
|
Python3
def findClosest(arr, n, target):
if (target < = arr[ 0 ]):
return arr[ 0 ]
if (target > = arr[n - 1 ]):
return arr[n - 1 ]
i = 0 ; j = n; mid = 0
while (i < j):
mid = (i + j) / / 2
if (arr[mid] = = target):
return arr[mid]
if (target < arr[mid]) :
if (mid > 0 and target > arr[mid - 1 ]):
return getClosest(arr[mid - 1 ], arr[mid], target)
j = mid
else :
if (mid < n - 1 and target < arr[mid + 1 ]):
return getClosest(arr[mid], arr[mid + 1 ], target)
i = mid + 1
return arr[mid]
def getClosest(val1, val2, target):
if (target - val1 > = val2 - target):
return val2
else :
return val1
arr = [ 1 , 2 , 4 , 5 , 6 , 6 , 8 , 9 ]
n = len (arr)
target = 11
print (findClosest(arr, n, target))
|
C#
using System;
class GFG
{
public static int findClosest( int []arr,
int target)
{
int n = arr.Length;
if (target <= arr[0])
return arr[0];
if (target >= arr[n - 1])
return arr[n - 1];
int i = 0, j = n, mid = 0;
while (i < j)
{
mid = (i + j) / 2;
if (arr[mid] == target)
return arr[mid];
if (target < arr[mid])
{
if (mid > 0 && target > arr[mid - 1])
return getClosest(arr[mid - 1],
arr[mid], target);
j = mid;
}
else
{
if (mid < n-1 && target < arr[mid + 1])
return getClosest(arr[mid],
arr[mid + 1], target);
i = mid + 1;
}
}
return arr[mid];
}
public static int getClosest( int val1, int val2,
int target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
public static void Main()
{
int []arr = {1, 2, 4, 5,
6, 6, 8, 9};
int target = 11;
Console.WriteLine(findClosest(arr, target));
}
}
|
Javascript
<script>
function findClosest(arr, target)
{
let n = arr.length;
if (target <= arr[0])
return arr[0];
if (target >= arr[n - 1])
return arr[n - 1];
let i = 0, j = n, mid = 0;
while (i < j)
{
mid = (i + j) / 2;
if (arr[mid] == target)
return arr[mid];
if (target < arr[mid])
{
if (mid > 0 && target > arr[mid - 1])
return getClosest(arr[mid - 1],
arr[mid], target);
j = mid;
}
else
{
if (mid < n - 1 && target < arr[mid + 1])
return getClosest(arr[mid],
arr[mid + 1],
target);
i = mid + 1;
}
}
return arr[mid];
}
function getClosest(val1, val2, target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
let arr = [ 1, 2, 4, 5, 6, 6, 8, 9 ];
let target = 11;
document.write(findClosest(arr, target));
</script>
|
PHP
<?php
function findClosest( $arr , $n , $target )
{
if ( $target <= $arr [0])
return $arr [0];
if ( $target >= $arr [ $n - 1])
return $arr [ $n - 1];
$i = 0;
$j = $n ;
$mid = 0;
while ( $i < $j )
{
$mid = ( $i + $j ) / 2;
if ( $arr [ $mid ] == $target )
return $arr [ $mid ];
if ( $target < $arr [ $mid ])
{
if ( $mid > 0 && $target > $arr [ $mid - 1])
return getClosest( $arr [ $mid - 1],
$arr [ $mid ], $target );
$j = $mid ;
}
else
{
if ( $mid < $n - 1 &&
$target < $arr [ $mid + 1])
return getClosest( $arr [ $mid ],
$arr [ $mid + 1], $target );
$i = $mid + 1;
}
}
return $arr [ $mid ];
}
function getClosest( $val1 , $val2 , $target )
{
if ( $target - $val1 >= $val2 - $target )
return $val2 ;
else
return $val1 ;
}
$arr = array ( 1, 2, 4, 5, 6, 6, 8, 9 );
$n = sizeof( $arr );
$target = 11;
echo (findClosest( $arr , $n , $target ));
?>
|
Time Complexity: O(log n) (Due to Binary Search)
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.
Initialize left = 0 and right = n-1, where n is the size of the array.
Loop while left < right
a. 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++
b. Else, move right pointer one step to the left, i.e. right–
Return arr[left], which will be the element closest to the target.
C++
#include <bits/stdc++.h>
using namespace std;
int findClosest( int arr[], int n, int target)
{
int left = 0, right = n - 1;
while (left < right) {
if ( abs (arr[left] - target)
<= abs (arr[right] - target)) {
right--;
}
else {
left++;
}
}
return arr[left];
}
int main()
{
int arr[] = { 1, 2, 4, 5, 6, 6, 8, 8, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
int target = 11;
cout << findClosest(arr, n, target);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int findClosest( int [] arr, int n,
int target)
{
int left = 0 , right = n - 1 ;
while (left < right) {
if (Math.abs(arr[left] - target)
<= Math.abs(arr[right] - target)) {
right--;
}
else {
left++;
}
}
return arr[left];
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 4 , 5 , 6 , 6 , 8 , 8 , 9 };
int n = arr.length;
int target = 11 ;
System.out.println(findClosest(arr, n, target));
}
}
|
Python3
import sys
def findClosest(arr, n, target):
left, right = 0 , n - 1
while left < right:
if abs (arr[left] - target) < = abs (arr[right] - target):
right - = 1
else :
left + = 1
return arr[left]
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 5 , 6 , 6 , 8 , 8 , 9 ]
n = len (arr)
target = 11
print (findClosest(arr, n, target))
|
C#
using System;
public class Program {
static int FindClosest( int [] arr, int n, int target)
{
int left = 0, right = n - 1;
while (left < right) {
if (Math.Abs(arr[left] - target)
<= Math.Abs(arr[right] - target)) {
right--;
}
else {
left++;
}
}
return arr[left];
}
static void Main( string [] args)
{
int [] arr = { 1, 2, 4, 5, 6, 6, 8, 8, 9 };
int n = arr.Length;
int target = 11;
Console.WriteLine(FindClosest(arr, n, target));
}
}
|
Javascript
function findClosest(arr, n, target) {
let left = 0, right = n-1;
while (left < right) {
if (Math.abs(arr[left] - target) <= Math.abs(arr[right] - target)) {
right--;
} else {
left++;
}
}
return arr[left];
}
const arr = [1, 2, 4, 5, 6, 6, 8, 8, 9];
const n = arr.length;
const target = 11;
console.log(findClosest(arr, n, target));
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 3: Recursive Approach
- “findClosestRecursive” function takes an array “arr” , right and left indices of the current search range and integer traget.
- “findClosestRecursive” function usese binary search approach to recursively search array.
- “findClosestRecursive” function also calculates the middle index of the current search range and recursively searches the left and right halves of the array.
- Base case – It occurs when there is only one element in an array. In that case, function will simply returns that element.
C++
#include <bits/stdc++.h>
using namespace std;
int findClosestRecursive( int arr[], int left, int right, int target) {
if (left == right) {
return arr[left];
}
int mid = (left + right) / 2;
int leftClosest = findClosestRecursive(arr, left, mid, target);
int rightClosest = findClosestRecursive(arr, mid + 1, right, target);
if ( abs (leftClosest - target) <= abs (rightClosest - target)) {
return leftClosest;
}
else {
return rightClosest;
}
}
int main() {
int arr[] = {1, 2, 4, 5, 6, 6, 8, 8, 9};
int n = sizeof (arr) / sizeof (arr[0]);
int target = 11;
cout << findClosestRecursive(arr, 0, n-1, target);
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static int findClosestRecursive( int [] arr,
int left,
int right,
int target)
{
if (left == right) {
return arr[left];
}
int mid = (left + right) / 2 ;
int leftClosest
= findClosestRecursive(arr, left, mid, target);
int rightClosest = findClosestRecursive(
arr, mid + 1 , right, target);
if (Math.abs(leftClosest - target)
<= Math.abs(rightClosest - target)) {
return leftClosest;
}
else {
return rightClosest;
}
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 4 , 5 , 6 , 6 , 8 , 8 , 9 };
int n = arr.length;
int target = 11 ;
System.out.println(
findClosestRecursive(arr, 0 , n - 1 , target));
}
}
|
Python
def find_closest_recursive(arr, left, right, target):
if left = = right:
return arr[left]
mid = (left + right) / / 2
left_closest = find_closest_recursive(arr, left, mid, target)
right_closest = find_closest_recursive(arr, mid + 1 , right, target)
if abs (left_closest - target) < = abs (right_closest - target):
return left_closest
else :
return right_closest
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 5 , 6 , 6 , 8 , 8 , 9 ]
n = len (arr)
target = 11
print (find_closest_recursive(arr, 0 , n - 1 , target))
|
C#
using System;
public class GFG
{
static int FindClosestRecursive( int [] arr, int left, int right, int target)
{
if (left == right)
{
return arr[left];
}
int mid = (left + right) / 2;
int leftClosest = FindClosestRecursive(arr, left, mid, target);
int rightClosest = FindClosestRecursive(arr, mid + 1, right, target);
if (Math.Abs(leftClosest - target) <= Math.Abs(rightClosest - target))
{
return leftClosest;
}
else
{
return rightClosest;
}
}
static void Main( string [] args)
{
int [] arr = { 1, 2, 4, 5, 6, 6, 8, 8, 9 };
int n = arr.Length;
int target = 11;
Console.WriteLine(FindClosestRecursive(arr, 0, n - 1, target));
}
}
|
Javascript
function findClosestRecursive(arr, left, right, target) {
if (left == right) {
return arr[left];
}
let mid = Math.floor((left + right) / 2);
let leftClosest = findClosestRecursive(arr, left, mid, target);
let rightClosest = findClosestRecursive(arr, mid + 1, right, target);
if (Math.abs(leftClosest - target) <= Math.abs(rightClosest - target)) {
return leftClosest;
} else {
return rightClosest;
}
}
let arr = [1, 2, 4, 5, 6, 6, 8, 8, 9];
let n = arr.length;
let target = 11;
console.log(findClosestRecursive(arr, 0, n - 1, target));
|
Time Complexity: O(log n)
Auxiliary Space: O(log n)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!