Binary Search And Feasibility Optimization
Asked of: Software Engineer
Last updated

What's being tested
This tests binary search correctness: loop invariants, boundary updates, duplicate handling, and safe midpoint calculation. It also tests binary-search-on-answer, where you minimize a feasible value k using a monotonic predicate, plus basic subset-sum dynamic programming for combinatorial feasibility.
Patterns & templates
-
Classic binary search —
`binary_search`(nums,target) inO(log n)time,O(1)space; usemid = lo + (hi - lo) // 2. -
First occurrence / lower bound — find smallest index with
nums[i] >= target; use half-open interval[lo, hi)to reduce off-by-one errors. -
Last occurrence / upper bound — find largest index with
nums[i] <= target; implement via`upper_bound`(target) - 1 and validate bounds afterward. -
Recursive binary search — same invariant as iterative version, but
O(log n)stack space; always define base case before computingmid. -
Binary search on answer — search
kover[1, max(workloads)]; predicatecan_finish(k)must be monotonic and usually costsO(n). -
Minimum feasible rate — if
hours(k) = sum(ceil(x / k)), then largerknever increases hours; total complexityO(n log M). -
Subset sum DP —
`can_sum`(nums,target) via boolean arraydp[target+1], update descending;O(n * target)time,O(target)space.
Common pitfalls
Pitfall: Updating
lo = midorhi = midwithout progress can infinite-loop; uselo = mid + 1when discardingmid.
Pitfall: Returning
midimmediately for duplicates fails first/last occurrence variants; keep searching after recording a candidate.
Pitfall: Treating subset sum as greedy is wrong; use DP unless constraints clearly allow meet-in-the-middle or bitset optimization.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Featured in interview prep guides
Practice questions
- Solve BFS and grid tasksUber · Software Engineer · Onsite · medium
- Implement binary search variantsUber · Software Engineer · Onsite · Medium
- Solve minimum rate and subset sumUber · Software Engineer · Technical Screen · Medium
- Solve vault rate and subset-sumUber · Software Engineer · Technical Screen · Medium
- Find minimal rate k and subset sumUber · Software Engineer · Technical Screen · Medium
- Implement rate limiter, top-K, scheduler algorithmsUber · Software Engineer · Onsite · Medium
- Implement binary search from scratchUber · Software Engineer · Onsite · Medium
Related concepts
- Binary Search On AnswerCoding & Algorithms
- Binary Search, Partitioning, And Convex SearchCoding & Algorithms
- Sliding Window, Binary Search, and Prefix ReasoningCoding & Algorithms
- Array Search, Selection, And Dynamic ProgrammingCoding & Algorithms
- BST Algorithms And Lowest Common AncestorCoding & Algorithms
- Greedy, Heaps, And Scheduling OptimizationCoding & Algorithms