DEV Community

Discussion on: Challenge: Get Closest Number in an Array

Collapse
 
kennethlum profile image
Kenneth Lum • Edited

It looks like the array is sorted. If it is sorted, then the following should be optimal:

Binary search for the left insertion point, and then for the right insertion point.

If found, then that's the answer.

Otherwise, check the left or right number and see which one is closer to the target.

Time complexity: O(log n)