Algorithmsarray binary search

Binary Search in Array Variants

TT
Testlaa Team
May 14, 20261 min read

Interviewers love small twists: rotated sorted array, duplicates, or searching on a virtual array built from two lists. The trick is still monotonicity in the part you search.

Try this in Python

def search_rotated(nums: list[int], target: int) -> bool:
    """Classic pattern sketch: one half is always normally sorted."""
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return True
        # Students: finish cases by comparing endpoints; this is a template stub.
        if nums[lo] <= nums[mid]:  # left half sorted
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return False


print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0))

Key takeaways

  • Identify which side is sorted.
  • Use inclusive boundaries carefully when duplicates exist.
  • Start from classic sorted search before rotated variants.

Tags:

Binary searchPythonStudents