Binary search for 7 and show its index.
Acceptance criteria
- 1.#out should show index 3.
DSA Tutorial · Searching
These 10 tasks go with the Binary Search Explained chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “Binary search is four lines and almost everyone gets it wrong the first time. The logic is easy; the boundaries are where it breaks.” .
1.Find a valueexercise · easy · 10 min
Binary search for 7 and show its index.
Passes when: #out should show index 3.
2.Report a missexercise · easy · 10 min · practice plan
Search for a value that is absent and report it.
Passes when: #out should show absent.
3.Safe midpointexercise · easy · 10 min · practice plan
Compute a midpoint with the unsigned shift and show it.
Passes when: #out should show mid 2.
4.Count the stepsexercise · easy · 10 min · practice plan
Count how many halvings a search over eight items takes.
Passes when: #out should show three steps.
5.Requires sorted inputexercise · medium · 10 min · practice plan
Report whether binary search is valid on unsorted data.
Passes when: #out should show needs sorting.
6.Fix the bound that never shrinksbug fix · easy · 8 min
Setting low to mid rather than mid plus one stalls, so a guard stops it.
Passes when: #out should show index 4.
7.Fix the strict loop conditionbug fix · medium · 8 min · practice plan
Using < instead of <= skips the final single-element check.
Passes when: #out should show index 2.
8.Fix the reversed comparisonbug fix · easy · 8 min · practice plan
Moving the wrong bound searches away from the target.
Passes when: #out should show index 3.
9.Fix the search on unsorted databug fix · easy · 8 min · practice plan
Binary search assumes order, so the array must be sorted first.
Passes when: #out should show index 2.
10.Fix the midpoint left as a fractionbug fix · easy · 8 min · practice plan
Averaging with division gives 2.5, which is not a valid index.
Passes when: #out should show whole index.
Between them these tasks cover Midpoints, Loop bounds and Sorted input.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.