LeetCopilot Logo
LeetCopilot
Home/Learning Tools/Binary Search Visualizer

Binary Search Algorithm Visualizer

Interactive tool to master binary search patterns for coding interviews. Visualize classic O(log n) search, lower bound, and search in rotated arrays step-by-step.

Classic Binary Search

Step 1 / 0

Find the index of the target value in a sorted array. Returns -1 if not found. Target: 7

Ready to start
10
31
52
73
94
115
136
157
178
199
Python
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = left + (right - left) // 2
        
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
            
    return -1

Understanding Binary Search Patterns

Binary search is a fundamental algorithm that finds the position of a target value within a sorted array. By repeatedly dividing the search interval in half, it reduces the time complexity to O(log n), making it exponentially faster than linear search for large datasets. This pattern requires sorted data or a monotonic property.

Three Core Patterns

Classic Binary Search

Standard template to find a target in a sorted array. Returns index or -1 if not found.

Lower/Upper Bound

Finds the first or last occurrence of a target. Crucial for handling duplicates and insertion points.

Rotated Sorted Array

Determines which half is sorted to maintain O(log n) search even after array rotation.

Key Insight

The core principle of binary search is elimination. In each step, you compare the target with the middle element and confidently eliminate half of the remaining search space. This works because of the sorted nature of the data.

How to Use the Visualizer

  • Select a algorithm variant (Classic, Lower Bound, Rotated)
  • Use Next/Previous buttons to step through the comparison logic
  • Watch the Left, Right, and Mid pointers update in real-time
  • Observe how the search range (highlighted area) shrinks by half each step
  • Use Auto Play to visualize the O(log n) convergence

Practice Problems

Apply what you've learned with these LeetCode problems:

Binary Search (LC 704) - Classic pattern
Search Insert Position (LC 35) - Lower bound logic

Learn More

Explore our comprehensive binary search tutorials and guides:

Want to Practice LeetCode Smarter?

LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.

Also compatible with Edge, Brave, and Opera