Each subpattern solves a specific type of problem. Click on a card to view its template.
Template for: Classic Binary Search
Initialise lo = 0 and hi = n - 1 to cover the full sorted range.
mid = lo + (hi - lo) / 2 avoids integer overflow compared to (lo + hi) / 2.
If arr[mid] == target return mid. If arr[mid] < target set lo = mid + 1, else hi = mid - 1.
Loop exits when lo > hi — target not found, return -1 (or lo for insertion point).
1// Classic binary search — sorted array, exact match2int binarySearch(vector<int>& arr, int target)3{4 int lo = 0;5 int hi = (int)arr.size() - 1;67 while (lo <= hi)8 {9 int mid = lo + (hi - lo) / 2;1011 if (arr[mid] == target)12 {13 return mid; // found14 }15 else if (arr[mid] < target)16 {17 lo = mid + 1; // search right half18 }19 else20 {21 hi = mid - 1; // search left half22 }23 }2425 return -1; // not found (return lo for insertion index)26}
Sharpen your skills with hand-picked problems.
LeetCode #704
LeetCode #35
LeetCode #69
LeetCode #374
LeetCode #34
LeetCode #278
LeetCode #852
LeetCode #153
LeetCode #33
LeetCode #81
LeetCode #154
LeetCode #162
LeetCode #875
LeetCode #1011
LeetCode #1482
LeetCode #410
LeetCode #1552
LeetCode #74
LeetCode #240
LeetCode #378
LeetCode #1351
LeetCode #4
LeetCode #719
LeetCode #778
LeetCode #878