Binary search Flashcards

(7 cards)

1
Q

LeetCode 704 – Binary Search
Given sorted array + target → return index or -1.

A

Maintain [lo, hi] (inclusive) or [lo, hi) (half-open) invariant.

Loop: mid = lo + (hi-lo)/2; compare and shrink to the half that can contain target.

Stop when range empty; verify.

Time O(log n), Space O(1).

Tags: Binary Search template, Invariants.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

LeetCode 74 – Search a 2D Matrix
Rows sorted; first of each row > last of previous row; search target.

A

Treat matrix as flattened sorted array of size m*n.

Binary search over [0, m*n); map idx → (idx/n, idx%n).

Time O(log(mn)), Space O(1).

(Alt: binary search row, then within row.)

Tags: Binary Search on index mapping.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

LeetCode 875 – Koko Eating Bananas
Min integer speed k to eat all piles within h hours.

A

Binary search on answer k in [1, max(pile)].

Feasibility: hours needed = sum(ceil(p/k)) ≤ h ?

If feasible → search left; else → right.

Time O(n log maxPile).

Tags: BS on answer, Feasibility check.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

LeetCode 153 – Find Min in Rotated Sorted Array (no dups)

A

Compare nums[mid] with nums[hi]:

If mid > hi → min in right half (lo = mid+1).

Else → min in left incl. mid (hi = mid).

End at lo == hi → nums[lo].

Time O(log n).

Tags: Rotated array, Right-biased BS.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

LeetCode 33 – Search in Rotated Sorted Array
Find target; array rotated, no duplicates.

A

At each step one half is sorted.

If nums[lo] ≤ nums[mid] (left sorted): check if target in [lo, mid].

If yes, hi = mid-1; else lo = mid+1.

Else (right sorted): check [mid, hi] similarly.

Time O(log n).

Tags: Rotated BS, Half identification.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

LeetCode 981 – Time Based Key-Value Store
set(key, value, timestamp); get(key, timestamp) → value with greatest ts ≤ timestamp.

A

For each key, store sorted list of (timestamp, value).

get: binary search by timestamp to find rightmost ≤ t.

set: append (timestamps strictly increasing per key).

Time: set O(1), get O(log n).

Tags: BS on timestamps, Per-key arrays.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

LeetCode 4 – Median of Two Sorted Arrays
Two sorted arrays; find median in O(log(m+n)).

A

Binary search partition on the smaller array.

Choose i in A, j = half - i in B s.t. A[i-1] ≤ B[j] and B[j-1] ≤ A[i].

Median = average/max of the borders depending on parity.

Handle edges with ±∞ sentinels.

Time O(log min(m,n)), Space O(1).

Tags: BS on partition, Array math.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly