Python find index of closest value in sorted list
Given a sorted array and a number x, find the pair in array whose sum is closest to xGiven a sorted array and a number x, find a pair in an array whose sum is closest to x. Examples: Attention reader! Dont stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course. In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students. A simple solution is to consider every pair and keep track of the closest pair (the absolute difference between pair sum and x is minimum). Finally, print the closest pair. The time complexity of this solution is O(n2) An efficient solution can find the pair in O(n) time. The idea is similar to method 1 of this post. The following is a detailed algorithm. 1) Initialize a variable diff as infinite (Diff is used to store the difference between pair and x). We need to find the minimum diff. 2) Initialize two index variables l and r in the given sorted array. (a) Initialize first to the leftmost index: l = 0 (b) Initialize second the rightmost index: r = n-1 3) Loop while l < r. (a) If abs(arr[l] + arr[r] - sum) < diff then update diff and result (b) If(arr[l] + arr[r] < sum ) then l++ (c) Else r--Following is the implementation of the above algorithm. C++14
Java
Python3
C#
PHP
Javascript
Output
The closest pair is 22 and 30
Time Complexity: O(n), where n is the length of an Array. https://www.youtube.com/watch?v=QMWBRnolFCU This article is contributed by Harsh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Article Tags :
Arrays Searching Sorting
two-pointer-algorithm Practice Tags :
two-pointer-algorithm Arrays Searching Sorting
Read Full Article
|