Prepin
Log in

Locate the nearest value in a sorted array.

Approach / Explanation

This question seeks an algorithm that identifies the number in a sorted array that is nearest to a specified target number. This task is a typical application of the Binary Search algorithm, and having a solid understanding of it can be quite beneficial for candidates in interviews. Given a sorted array and a target number, your goal is to locate the number that is closest to that target. Important considerations include: Because the array is sorted, you can utilize this characteristic to halve the search space with each step, which is fundamental to the Binary Search algorithm. Keep in mind that the 'closest' number may be less than, equal to, or greater than the target number. You should also account for scenarios where the target number is either lower than the smallest number in the array or higher than the largest number.

Suggested Answer

We can address this issue using an iterative Binary Search approach. The core concept involves comparing the target value with the middle element of the array: if the target matches the middle element, we have found it; if the target is smaller, we focus on the left section of the array; and if the target is larger, we examine the right section of the array. Below is a Python implementation of this method: def find_closest ( nums , target ) : low = 0 high = len ( nums ) - 1 while low < high : mid = ( low + high ) // 2 if nums [ mid ] == target : return nums [ mid ] elif nums [ mid ] < target : low = mid + 1 else : high = mid - 1 # After the loop, low and high should indicate the two numbers # closest to the target. Select the nearest one. if low == 0 : return nums [ 0 ] if low == len ( nums ) : return nums [ - 1 ] if abs ( nums [ low ] - target ) < abs ( nums [ low - 1 ] - target ) : return nums [ low ] return nums [ low - 1 ]

Alternative Answer

As an alternative, we can employ a similar yet slightly modified technique that shifts the high and low pointers inward from the array's edges. This method circumvents the problem faced by the first approach regarding the decision to move left or right. Below is a Python example demonstrating this technique: def find_closest ( nums , target ) : low = 0 high = len ( nums ) - 1 while low < high : mid = ( low + high ) // 2 if nums [ mid ] < target : low = mid + 1 else : high = mid # After the loop, check which one is closest if low > 0 and abs ( nums [ low ] - target ) >= abs ( nums [ low - 1 ] - target ) : return nums [ low - 1 ] else : return nums [ low ]

Question Details

Difficulty & Category

Medium
algorithms

Companies

DoorDash

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.