Searching Algorithms

πŸ“– Introduction

Searching is about finding information efficiently. The first time I reduced a search from O(n) to O(log n), I watched a query that took seconds drop to milliseconds. That experience taught me that choosing the right search strategy can make or break an application's performance.

Binary search in particular is deceptively simple but incredibly powerful. Once you understand that it's not just about "finding an element in a sorted array" but about "searching over any monotonic space," entire categories of problems become solvable.


The simplest approachβ€”check each element sequentially.

def linear_search(arr: list, target) -> int:
    """
    Search for target in unsorted array.
    Time: O(n)
    Space: O(1)
    """
    for i, val in enumerate(arr):
        if val == target:
            return i
    return -1


# When to use linear search:
# - Unsorted data
# - Small datasets
# - Single search (not worth sorting first)
# - Linked lists (no random access)

Repeatedly divide search space in half. Requires sorted data.

spinner

Python's bisect Module


🎯 Binary Search Variations

Find First Occurrence

Find Last Occurrence

Search Range

Lower and Upper Bound


πŸ”„ Search in Rotated Arrays

Search in Rotated Sorted Array

Find Minimum in Rotated Array


πŸ“Š Search Space Problems

The key insight: binary search works on any monotonic function.

Square Root

Find Peak Element

Search 2D Matrix

Capacity to Ship Packages

Koko Eating Bananas

Split Array Largest Sum


πŸ” Other Search Techniques

For unimodal functions (single peak/valley).

When array size is unknown or infinite.


πŸ“ Practice Exercises

Exercise 1: First Bad Version

chevron-rightSolutionhashtag

Exercise 2: Find Smallest Letter Greater Than Target

chevron-rightSolutionhashtag

Exercise 3: Median of Two Sorted Arrays

chevron-rightSolutionhashtag

πŸ”‘ Key Takeaways

  1. Binary search achieves O(log n) by halving search space

  2. Use bisect module for Python's optimized binary search

  3. Search on answer when you can verify a candidate solution

  4. Rotated arrays require identifying the sorted portion

  5. Template matters: left <= right vs left < right

  6. Think monotonically: binary search works on any monotonic property


πŸš€ What's Next?

In the next article, we'll explore dynamic programming:

  • Identifying DP problems

  • Top-down vs bottom-up approaches

  • Classic DP patterns

  • Space optimization

Next: Article 12 - Dynamic Programming


πŸ“š References

  • CLRS Chapter 11: Hash Tables (binary search)

  • "Elements of Programming Interviews" - Binary Search chapter

  • Python bisect module documentation

Last updated