Introduction and Overview

Welcome back! Today, we're adding another tool to our toolkit for algorithms and data structures — a powerful searching technique known as binary search that operates seamlessly on sorted arrays. By the end of this session, you will understand binary search, its internals, its Python implementation, and its time and space complexity.

Drawing a parallel with everyday life, binary search resembles the process of finding a word in a dictionary. Instead of skimming through every page, we open the dictionary around the middle and compare our words. If our word is in the left half, we discard the right half, and vice versa. This halving process continues until we find our word — essentially, this is a binary search.

Understanding Binary Search

Binary Search is a search algorithm operating on a sorted list or array. The strategy employed by Binary Search is similar to the process of searching for a name in a telephone directory or a word in the dictionary - you open the book in the middle and determine whether the name or word you're looking for can be found in the left (first half) or the right part (second half). If the name or word you're searching for is smaller than the one in the middle, you continue your search only in the left half. However, if it's larger, you narrow down your search to the right half. This method is iteratively repeated, reducing the search space by half each time, thereby making this search operation highly effective.

In Python terms, imagine you have a sorted list of numbers as: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], and you've been tasked with determining if the number 3 is present in the list. With Binary Search, it directly jumps to the middle. If the number is equal to the middle element, our search is complete. But if the number is smaller than the middle element, Binary Search discards the second half of the list and continues the search only on the first half. This process is repeated until the number is found.

Binary Search Algorithm

Binary search uses a divide-and-conquer approach to find a specific element in a list. Regarding time complexity, this algorithm accomplishes the task in the order of , making it a preferable choice for large datasets.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal