Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DEV Community

Nitinn S Kulkarni
Nitinn S Kulkarni

Posted on

Part 7: Searching Algorithms in Python โ€“ Mastering Binary Search and Beyond

๐Ÿš€ Introduction

Searching is one of the most common operations in programming, and binary search is the crown jewel โ€” fast, efficient, and widely applicable.

In this post, weโ€™ll explore:

โœ… Linear Search vs Binary Search

โœ… Binary search templates in Python

โœ… Real-world problems using binary search

โœ… Lower/Upper bound techniques

โœ… Searching in rotated arrays and 2D matrices

๐Ÿ”Ž 1๏ธโƒฃ Linear Search โ€“ Simple but Slow**


def linear_search(arr, target):
    for i, num in enumerate(arr):
        if num == target:
            return i
    return -1

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Time Complexity: O(n)

โœ… Best for small or unsorted arrays

โŒ Not efficient for large datasets

โšก 2๏ธโƒฃ Binary Search โ€“ Fast and Precise

Works on sorted arrays by dividing the search space in half at each step.


def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Time Complexity: O(log n)

โœ… Must be sorted

โœ… Used in both 1D and 2D problems

๐Ÿ” 3๏ธโƒฃ Binary Search Template (Lower Bound Style)

This version is more flexible and forms the base of many variations.


def lower_bound(arr, target):
    left, right = 0, len(arr)
    while left < right:
        mid = (left + right) // 2
        if arr[mid] < target:
            left = mid + 1
        else:
            right = mid
    return left

Enter fullscreen mode Exit fullscreen mode

โœ… Finds the first position where target can be inserted.

๐Ÿงช 4๏ธโƒฃ Real Problems Using Binary Search

๐Ÿ”น Search Insert Position


def search_insert(nums, target):
    left, right = 0, len(nums)
    while left < right:
        mid = (left + right) // 2
        if nums[mid] < target:
            left = mid + 1
        else:
            right = mid
    return left

Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Find First and Last Position of an Element


def find_first_last(nums, target):
    def find_bound(is_left):
        left, right = 0, len(nums)
        while left < right:
            mid = (left + right) // 2
            if nums[mid] > target or (is_left and nums[mid] == target):
                right = mid
            else:
                left = mid + 1
        return left

    left = find_bound(True)
    right = find_bound(False) - 1
    if left <= right and right < len(nums) and nums[left] == target and nums[right] == target:
        return [left, right]
    return [-1, -1]

Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Search in Rotated Sorted Array


def search_rotated(nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        if nums[left] <= nums[mid]:
            if nums[left] <= target < nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        else:
            if nums[mid] < target <= nums[right]:
                left = mid + 1
            else:
                right = mid - 1
    return -1

Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Binary Search in 2D Matrix


def search_matrix(matrix, target):
    if not matrix or not matrix[0]:
        return False

    m, n = len(matrix), len(matrix[0])
    left, right = 0, m * n - 1

    while left <= right:
        mid = (left + right) // 2
        val = matrix[mid // n][mid % n]
        if val == target:
            return True
        elif val < target:
            left = mid + 1
        else:
            right = mid - 1

    return False

Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ 5๏ธโƒฃ Advanced Use Cases

๐Ÿ”ธ Minimize the Maximum (Binary Search on Answer)

Use binary search on the value space, not index. Example:

- Minimum capacity to ship packages in D days

  • Min max distance to place routers

  • Minimize largest subarray sum

Enter fullscreen mode Exit fullscreen mode




๐Ÿ“Š 6๏ธโƒฃ Comparison Summary

Method Time Use Case
Linear Search O(n) Unsorted or small datasets
Binary Search O(log n) Sorted 1D arrays
2D Binary Search O(log m*n) Sorted matrices
Binary on Answer Varies Optimization problems

โœ… Best Practices

โœ”๏ธ Always check if the array is sorted before applying binary search
โœ”๏ธ Use while left < right or while left <= right as per problem
โœ”๏ธ Avoid infinite loops: always update left/right
โœ”๏ธ Try implementing both upper and lower bound logic
โœ”๏ธ For rotated arrays โ€“ think in terms of sorted halves

๐Ÿง  Summary

โœ”๏ธ Binary search is the go-to method for efficient searching in sorted data
โœ”๏ธ Understand different templates for flexible use
โœ”๏ธ Learn to use it in 1D, 2D, and even on value space
โœ”๏ธ A must-have technique for interviews and system optimization

๐Ÿ”œ Coming Up Next:

๐Ÿ‘‰ Part 8: Trees and Binary Trees โ€“ Traversals, Depth, and Recursive Patterns

Weโ€™ll cover:

1. DFS & BFS

  1. Inorder, Preorder, Postorder
  2. Balanced trees, height, diameter
  3. Binary Search Tree (BST) basics
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ฌ Have a binary search trick or a real interview example? Letโ€™s chat in the comments! ๐Ÿ”Ž๐Ÿ

Top comments (0)