🌇DSA
← Back
AlgorithmBeginner
🔎

Search Algorithms

Find items efficiently

⏱️ 5–9 hours🧩 10 LeetCode
🔒 Login to unlock solutions and track progress. Login

What is it?

Searching means finding a value inside a collection.

Think of finding a word in a dictionary:

  • Linear search — read every word from page 1 until you find it (slow but works anywhere).
  • Binary search — open the middle, decide if your word is before or after, then repeat in the correct half (fast but needs the dictionary to be sorted).

Common Variants

  • Binary Search on value — find a target in a sorted array
  • Binary Search on answer — guess a value and check if it satisfies a condition
  • Search in rotated array — binary search with an extra pivot check
  • Search in 2D matrix — treat each row or column as sorted

Real-World Examples

Ctrl+F in a document
Sorted contact lookup
Price range filtering
Git bisect (find bad commit)
Square root by guess
Database index lookup

Code Example

What this code shows

Binary search on sorted [1,3,5,7,9,11]. To find 7: check middle (5), 7>5 so move right, check middle (9), 7<9 so move left, find 7 at index 3. To find 4: same process but never matches → return -1.

function binarySearch(arr, target) {
let lo = 0;
let hi = arr.length - 1;

while (lo <= hi) {
  const mid = Math.floor((lo + hi) / 2); // pick the middle index

  if (arr[mid] === target) {
    return mid;          // found it!
  } else if (arr[mid] < target) {
    lo = mid + 1;        // target is in the RIGHT half
  } else {
    hi = mid - 1;        // target is in the LEFT half
  }
}

return -1; // not found
}

const arr = [1, 3, 5, 7, 9, 11];
console.log("Index of  7: ", binarySearch(arr, 7)); //  3
console.log("Index of  4: ", binarySearch(arr, 4)); // -1

Expected Output

Index of  7:  3
Index of  4: -1

LeetCode Practice