Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program for Find the closest pair from two sorted arrays
Next article icon

Python Program to Find closest number in array

Last Updated : 17 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.

Method #1: Using Binary search

Python3
# Python3 program to find element # closest to given target.  # Returns element closest to target in arr[]   def findClosest(arr, n, target):      # Corner cases     if (target <= arr[0]):         return arr[0]     if (target >= arr[n - 1]):         return arr[n - 1]      # Doing binary search     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 and 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 and target < arr[mid + 1]):                 return getClosest(arr[mid], arr[mid + 1], target)              # update i             i = mid + 1      # 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. def getClosest(val1, val2, target):      if (target - val1 >= val2 - target):         return val2     else:         return val1   # Driver code arr = [1, 2, 4, 5, 6, 6, 8, 9] n = len(arr) target = 11 print(findClosest(arr, n, target)) 

Output
9

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

Method #2: Using min() function

Python3
# Python3 program to find element # closest to given target.  def findClosestValue(givenList, target):      def difference(givenList):         return abs(givenList - target)      result = min(givenList, key=difference)      return result   if __name__ == "__main__":      givenList = [1, 2, 4, 5, 6, 6, 8, 9]      target = 11      result = findClosestValue(givenList, target)      print("The closest value to the " + str(target)+" is", result) # This code is contributed by  vikkycirus 

Output
The closest value to the 11 is 9

Method #3: 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
    • 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–-
  3. Return arr[left], which will be the element closest to the target.

Below is the implementation of the above approach:

Python3
# Python program to find element # closest to given target using two pointers 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))  # This code is contributed by Susobhan Akhuli 

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
Python Program for Find the closest pair from two sorted arrays
author
kartik
Improve
Article Tags :
  • Divide and Conquer
  • Searching
  • Python
  • Python Programs
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search
  • Divide and Conquer
  • python
  • Searching

Similar Reads

  • Python program to find the smallest number in a file
    Given a text file, write a Python program to find the smallest number in the given text file. Examples: Input: gfg.txtOutput: 9Explanation: Contents of gfg.txt: I live at 624 Hyderabad.My mobile number is 52367. My favourite number is 9.Numbers present in the text file are 9,624,52367Minimum number
    3 min read
  • Python Program for Find the closest pair from two sorted arrays
    Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. We are given two arrays ar1[0...m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] - x) is minimum.Exam
    2 min read
  • Python program to find smallest number in a list
    In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python's built-in min() function. Using min()The min() function takes an iterable (like a list, typle etc.) and returns the smallest value. [GFGTABS]
    3 min read
  • Python | Find closest number to k in given list
    Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K. Examples: Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1 Output : 9.35 Input : lst = [9, 11, 5, 3, 25, 18], K = 6 Output : 5 Method
    5 min read
  • Find Index of Element in Array - Python
    In Python, arrays are used to store multiple values in a single variable, similar to lists but they offer a more compact and efficient way to store data when we need to handle homogeneous data types . While lists are flexible, arrays are ideal when we want better memory efficiency or need to perform
    2 min read
  • Python Program for Find minimum sum of factors of number
    Given a number, find minimum sum of its factors.Examples: Input : 12Output : 7Explanation: Following are different ways to factorize 12 andsum of factors in different ways.12 = 12 * 1 = 12 + 1 = 1312 = 2 * 6 = 2 + 6 = 812 = 3 * 4 = 3 + 4 = 712 = 2 * 2 * 3 = 2 + 2 + 3 = 7Therefore minimum sum is 7Inp
    1 min read
  • Python Program to find the Next Nearest element in a Matrix
    Given a matrix, a set of coordinates and an element, the task is to write a python program that can get the coordinates of the elements next occurrence. Input : test_list = [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3], [8, 5, 3, 5, 3], [1, 2, 3, 4, 6]], i, j = 1, 3, K = 3 Output : (1, 4) Explanation : After (1
    4 min read
  • Find index of element in array in python
    We often need to find the position or index of an element in an array (or list). We can use an index() method or a simple for loop to accomplish this task. index() method is the simplest way to find the index of an element in an array. It returns the index of the first occurrence of the element we a
    2 min read
  • Python3 Program to 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: 3Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0Input: {0, 1, 2, 3}, n = 4, m = 5
    4 min read
  • Python3 Program to Find lost element from a duplicated array
    Given two arrays that are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element.Examples: Input: arr1[] = {1, 4, 5, 7, 9} arr2[] = {4, 5, 7, 9}Output: 11 is missing from second array.Input: arr1[] = {2, 3, 4, 5} arr2[]
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences