🔎 Searching Algorithms Master Guide

Searching is a core topic in computer science and interviews. This guide covers all major searching techniques, templates, and must-do problems.

📑 Table of Contents

  1. Overview & Keywords
  2. Must-Know Searching Algorithms
  3. Templates
  4. Key Patterns
  5. Practice Problems

Overview & Keywords

Searching is the process of finding an element or condition in a data structure. Common interview keywords:


Must-Know Searching Algorithms


Templates

int linearSearch(vector<int>& arr, int target) {
    for (int i = 0; i < arr.size(); i++) {
        if (arr[i] == target) return i;
    }
    return -1;
}

Binary Search (Basic)

int binarySearch(vector<int>& arr, int target) {
    int low = 0, high = arr.size() - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) return mid;
        else if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

Binary Search on Answer

int solve(vector<int>& arr) {
    int left = min_possible, right = max_possible, answer = -1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (isValid(mid)) {
            answer = mid;
            right = mid - 1; // or left = mid + 1 for max
        } else {
            left = mid + 1;
        }
    }
    return answer;
}

Key Patterns

Pattern Use When Example Problems
Linear Search Unsorted, small data Find element in array
Binary Search Sorted, monotonic, ranges First/last occurrence, peak
Binary Search on Answer Search space is monotonic Allocate books, Koko bananas

Practice Problems

Level 1 — Easy

Level 2 — Medium

Level 3 — Hard

410 ○ Unsolved

← Back to Searching & Sorting DSA Hub 🏠