Smallest Element that is larger than target
Given a sorted array, find the smallest element larger than target
sample array:
sssssssssssssss eeeeeeeeeeeeeee Bbbbbbbbbbbbbbbb
Three cases for mid:
mid = target, search right for last target element
mid < target, search right
mid > target, search left, including mid
Moving rule:
Left side pinches when on target or smaller than target
Right side pinches when larger than target
End condition:
two elements left in array, both >= target
Post Processing:
check left > target, then right > target, return -1
TC: O(logN) reduce by half each time
SC: O(1) no additional data structs used
Last updated
Was this helpful?