Minimum Absolute Difference Between Elements With Constraint — binary search
Halve the sorted range until the target is found or the range collapses. Built for LeetCode 2817. Minimum Absolute Difference Between Elements With Constraint.
Because the slice is sorted, comparing nums[mid] to target tells you which half can be thrown away. That is the whole algorithm.
Algorithm
- While
lo <= hi, pickmid. - Equal → return
mid. Too small → search right. Too big → search left. - Empty range → not found (
-1).
- Time
- O(log n)
- Space
- O(1)
class Solution: def minimumAbsoluteDifferenceBetweenElementsWithConstraint(self, nums: list[int], target: int) -> int: lo, hi = 0, len(nums) - 1 while lo <= hi: mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1