Count of Smaller Numbers After Self — binary search
Halve the sorted range until the target is found or the range collapses. Built for LeetCode 315. Count of Smaller Numbers After Self.
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 countOfSmallerNumbersAfterSelf(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