Javascript Program to Find closest number in array
Last Updated :
13 Apr, 2023
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.
JavaScript
<script>
// JavaScript program to find element
// closest to given target.
// Returns element closest to target in arr[]
function findClosest(arr, target)
{
let n = arr.length;
// Corner cases
if (target <= arr[0])
return arr[0];
if (target >= arr[n - 1])
return arr[n - 1];
// Doing binary search
let i = 0, j = n, mid = 0;
while (i < j)
{
mid = (i + j) / 2;
if (arr[mid] == target)
return arr[mid];
// If target is less than array
// element,then search in left
if (target < arr[mid])
{
// If target is greater than previous
// to mid, return closest of two
if (mid > 0 && target > arr[mid - 1])
return getClosest(arr[mid - 1],
arr[mid], target);
// Repeat for left half
j = mid;
}
// If target is greater than mid
else
{
if (mid < n - 1 && target < arr[mid + 1])
return getClosest(arr[mid],
arr[mid + 1],
target);
i = mid + 1; // update i
}
}
// Only single element left after search
return arr[mid];
}
// Method to compare which one is the more close
// We find the closest by taking the difference
// between the target and both values. It assumes
// that val2 is greater than val1 and target lies
// between these two.
function getClosest(val1, val2, target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
// Driver Code
let arr = [ 1, 2, 4, 5, 6, 6, 8, 9 ];
let target = 11;
document.write(findClosest(arr, target));
// This code is contributed by code_hunt
</script>
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:
- Initialize left = 0 and right = n-1, where n is the size of the array.
- Loop while left < right
- 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++
- Else, move right pointer one step to the left, i.e. right–-
- Return arr[left], which will be the element closest to the target.
Below is the implementation of the above approach:
JavaScript
<script>
//JavaScript program to find element
// closest to given target using two pointers
const 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));
// This code is contributed by Susobhan Akhuli
</script>
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!
Similar Reads
Find closest number in Sorted array 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,
13 min read
Javascript Program to Find a pair with the given difference Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78Output: Pair Found: (2, 80)Input: arr[] = {90, 70, 20, 80, 50}, n = 45Output: No Such PairNative Approach:The simplest method is t
4 min read
Javascript Program for Find the smallest missing number Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples:Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m =
4 min read
Closest K Elements in a Sorted Array You are given a sorted array arr[] containing unique integers, a number k, and a target value x. Your goal is to return exactly k elements from the array that are closest to x, excluding x itself if it is present in the array.An element a is closer to x than b if:|a - x| < |b - x|, or|a - x| == |
15+ min read
Smallest divisor of N closest to X Given two positive integers N and X, the task is to find the smallest divisor of N which is closest to X. Examples: Input: N = 16, X = 5 Output: 4 Explanation: 4 is the divisor of 16 which is closest to 5. Input: N = 27, X = 15Output: 9 Explanation:9 is the divisor of 27 closest to 15. Naive Approac
15+ min read
Subarray whose sum is closest to K Given an array of positive and negative integers and an integer K. The task is to find the subarray with its sum closest to k. In case of multiple answers, print anyone.Note: Closest here means abs(sum-k) should be minimal.Examples: Input: arr[] = [ -5, 12, -3, 4, -15, 6, 1 ], k = 2 Output: 1Explana
15 min read