Open In App

Closest value to K from an unsorted array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers and an integer K, the task is to find the array element closest to K. If multiple closest values exist, then print the smallest one.

Examples:

Input: arr[]={4, 2, 8, 11, 7}, K = 6
Output: 7
Explanation:
The absolute difference between 4 and 6 is |4 – 6| = 2
The absolute difference between 2 and 6 is |2 – 6| = 4
The absolute difference between 8 and 6 is |8– 6| = 2
The absolute difference between 11 and 6 is |11 – 6| = 5
The absolute difference between 7 and 6 is |7 – 6| = 1
Here, the absolute difference between K(=6) and 7 is minimum. Therefore, the closest value of K(=6) is 7

Input: arr[]={100, 200, 400}, K = 300
Output: 200

Approach: The idea is to traverse the given array and print an element of the array which gives the minimum absolute difference with the given integer K. Follow the steps below to solve the problem:

  1. Initialize a variable, say res, to store the array element the closest value to K.
  2. Traverse the array and compare the absolute value of abs(K – res) and the absolute value of abs(K – arr[i]).
  3. If the value of abs(K – res) exceeds abs(K – arr[i]), then update res to arr[i].
  4. Finally, print res.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to get
// the closest value
int clostVal(int arr[],
             int N,
             int K)
{
    // Stores the closest
    // value to K
    int res = arr[0];
 
    // Traverse the array
    for (int i = 1; i < N;
         i++) {
 
        // If absolute difference
        // of K and res exceeds
        // absolute difference of K
        // and current element
        if (abs(K - res) > abs(K - arr[i])) {
            res = arr[i];
        }
    }
 
    // Return the closest
    // array element
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 100, 200, 400 };
    int K = 300;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << clostVal(arr, N, K);
}


Java




// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
  
// Function to get
// the closest value
static int clostVal(int arr[], int N,
                    int K)
{
     
    // Stores the closest
    // value to K
    int res = arr[0];
  
    // Traverse the array
    for(int i = 1; i < N; i++)
    {
         
        // If absolute difference
        // of K and res exceeds
        // absolute difference of K
        // and current element
        if (Math.abs(K - res) >
            Math.abs(K - arr[i]))
        {
            res = arr[i];
        }
    }
  
    // Return the closest
    // array element
    return res;
}
  
// Driver Code
public static void main (String[] args)
{
    int arr[] = { 100, 200, 400 };
    int K = 300;
    int N = arr.length;
     
    System.out.print(clostVal(arr, N, K));
}
}
 
// This code is contributed by code_hunt


Python3




# Python3 program to implement
# the above approach
 
# Function to get
# the closest value
def clostVal(arr, N, K):
     
    # Stores the closest
    # value to K
    res = arr[0]
 
    # Traverse the array
    for i in range(1, N, 1):
 
        # If absolute difference
        # of K and res exceeds
        # absolute difference of K
        # and current element
        if (abs(K - res) >
            abs(K - arr[i])):
            res = arr[i]
 
    # Return the closest
    # array element
    return res
 
# Driver Code
arr = [ 100, 200, 400 ]
K = 300
N = len(arr)
 
print(clostVal(arr, N, K))
 
# This code is contributed by susmitakundugoaldanga


C#




// C# program to implement
// the above approach 
using System;
 
class GFG{
  
// Function to get
// the closest value
static int clostVal(int[] arr, int N,
                    int K)
{
     
    // Stores the closest
    // value to K
    int res = arr[0];
  
    // Traverse the array
    for(int i = 1; i < N; i++)
    {
         
        // If absolute difference
        // of K and res exceeds
        // absolute difference of K
        // and current element
        if (Math.Abs(K - res) >
            Math.Abs(K - arr[i]))
        {
            res = arr[i];
        }
    }
  
    // Return the closest
    // array element
    return res;
}
  
// Driver Code
public static void Main ()
{
    int[] arr = { 100, 200, 400 };
    int K = 300;
    int N = arr.Length;
     
    Console.WriteLine(clostVal(arr, N, K));
}
}
 
// This code is contributed by sanjoy_62


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to get
// the closest value
function clostVal(arr, N, K)
{
     
    // Stores the closest
    // value to K
    let res = arr[0];
  
    // Traverse the array
    for(let i = 1; i < N; i++)
    {
         
        // If absolute difference
        // of K and res exceeds
        // absolute difference of K
        // and current element
        if (Math.abs(K - res) >
            Math.abs(K - arr[i]))
        {
            res = arr[i];
        }
    }
  
    // Return the closest
    // array element
    return res;
}
 
// Driver Code
 
    let arr = [ 100, 200, 400 ];
    let K = 300;
    let N = arr.length;
     
    document.write(clostVal(arr, N, K));
 
</script>


Output: 

200

 

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 05 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads