Skip to content

Binary Search Algorithms ​

A comprehensive guide to mastering binary search algorithms for technical interviews. Binary search is one of the most fundamental and frequently tested algorithms in coding interviews.

πŸ“š Table of Contents ​

Binary search is a divide-and-conquer algorithm that efficiently finds a target value in a sorted array by repeatedly dividing the search interval in half.

Key Characteristics ​

  • Prerequisite: Array must be sorted
  • Strategy: Eliminate half of the search space in each iteration
  • Efficiency: O(log n) time complexity
  • Memory: O(1) space complexity (iterative)

Basic Algorithm Flow ​

1. Set left = 0, right = array.length - 1
2. While left <= right:
   a. Calculate mid = left + (right - left) / 2
   b. If array[mid] == target: return mid
   c. If array[mid] < target: left = mid + 1
   d. If array[mid] > target: right = mid - 1
3. Return -1 (not found)

Core Concepts ​

1. Search Space Reduction ​

typescript
// Each comparison eliminates half the remaining elements
[1, 3, 5, 7, 9, 11, 13, 15]  // 8 elements
       ↑ mid=7
// If target > 7, eliminate left half
             [9, 11, 13, 15]  // 4 elements
                ↑ mid=11
// Continue until found or exhausted

2. Boundary Handling ​

Critical Points:

  • Mid calculation: Use left + (right - left) / 2 to avoid overflow
  • Loop condition: left <= right vs left < right
  • Update strategy: left = mid + 1 vs left = mid

3. Variant Types ​

TypePurposeLoop ConditionUpdate Rule
ClassicFind exact matchleft <= rightleft = mid + 1, right = mid - 1
Left BoundFind first occurrenceleft < rightleft = mid + 1, right = mid
Right BoundFind last occurrenceleft < rightleft = mid, right = mid - 1

βœ… Perfect Scenarios ​

  1. Sorted Array Search

    • Finding exact value
    • Finding insertion position
    • Finding first/last occurrence
  2. Range Queries

    • First element β‰₯ target
    • Last element ≀ target
    • Count of elements in range
  3. Rotated Sorted Arrays

    • Search in rotated array
    • Find rotation point
    • Find minimum/maximum
  4. Binary Search on Answer

    • Optimization problems
    • Finding minimum/maximum feasible value
    • Resource allocation problems

❌ Not Suitable For ​

  • Unsorted arrays (sort first: O(n log n))
  • Linked lists (no random access)
  • Very small arrays (linear search might be faster)
  • When you need all occurrences

Common Patterns ​

typescript
// Find exact target in sorted array
function search(nums: number[], target: number): number {
    let left = 0, right = nums.length - 1;
    
    while (left <= right) {
        const mid = left + Math.floor((right - left) / 2);
        if (nums[mid] === target) return mid;
        else if (nums[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

Pattern 2: Find Boundaries ​

typescript
// Find first position where condition is true
function findFirst(nums: number[], target: number): number {
    let left = 0, right = nums.length - 1;
    let result = -1;
    
    while (left <= right) {
        const mid = left + Math.floor((right - left) / 2);
        if (nums[mid] >= target) {
            result = mid;
            right = mid - 1; // Continue searching left
        } else {
            left = mid + 1;
        }
    }
    return result;
}

Pattern 3: Binary Search on Answer ​

typescript
// Find minimum value that satisfies condition
function binarySearchAnswer(condition: (x: number) => boolean, 
                          left: number, right: number): number {
    while (left < right) {
        const mid = left + Math.floor((right - left) / 2);
        if (condition(mid)) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    return left;
}

Interview Tips ​

🎯 Problem Recognition ​

Look for these keywords:

  • "sorted array"
  • "find target"
  • "first/last occurrence"
  • "insertion position"
  • "rotated sorted"
  • "minimum/maximum that satisfies"

πŸ”§ Implementation Tips ​

  1. Always clarify requirements:

    • Exact match or closest?
    • First/last occurrence?
    • What to return if not found?
  2. Handle edge cases:

    • Empty array
    • Single element
    • Target not in array
    • All elements same
  3. Avoid common mistakes:

    • Integer overflow in mid calculation
    • Infinite loops (wrong update rules)
    • Off-by-one errors

πŸ§ͺ Testing Strategy ​

typescript
// Test cases to always consider:
const testCases = [
    { nums: [], target: 1 },           // Empty array
    { nums: [1], target: 1 },          // Single element (found)
    { nums: [1], target: 2 },          // Single element (not found)
    { nums: [1,2,3], target: 2 },      // Middle element
    { nums: [1,2,3], target: 1 },      // First element
    { nums: [1,2,3], target: 3 },      // Last element
    { nums: [1,2,3], target: 0 },      // Before range
    { nums: [1,2,3], target: 4 },      // After range
    { nums: [1,1,1], target: 1 },      // Duplicates
];

Problem Implementations ​

This directory contains the following problem solutions:

TypeScript Solutions ​

Documentation ​

  • Templates - Binary search code templates and patterns

Common Binary Search Problems ​

  1. Classic Binary Search: Find target in sorted array
  2. First/Last Occurrence: Find boundaries of target
  3. Rotated Array Search: Search in rotated sorted array
  4. Peak Element: Find local maximum
  5. Square Root: Find integer square root
  6. Search Insert Position: Find insertion point
  7. Minimum in Rotated Array: Find minimum element

Practice Problems ​

🟒 Easy ​

🟑 Medium ​

πŸ”΄ Hard ​

Time & Space Complexity ​

OperationTimeSpaceNotes
Classic SearchO(log n)O(1)Iterative implementation
Recursive SearchO(log n)O(log n)Due to call stack
Range SearchO(log n)O(1)Find start + end positions
2D Matrix SearchO(log(mΓ—n))O(1)Treat as 1D array

Resources ​

  • πŸ“– Templates: See templates.md for detailed code templates
  • 🎯 Practice: Work through problems in order of difficulty
  • πŸ“ Notes: Focus on boundary conditions and edge cases

Remember: Binary search is not just about finding elementsβ€”it's a powerful technique for optimization problems where you can "guess and check" efficiently! πŸš€

Software Engineer Interview Preparation