Binary Search
easy⏱ 15 mintypescriptchallengesproblem-solving-basic-
Runs in your browser
- Before starting
- Use a supported browser; initial dependencies may need internet.
- What it proves
- Run shows output; Test checks the authored cases, not every possible input.
- When finished
- Stop active runs when finished. No cloud infrastructure is provisioned by this exercise.
LEARN BY DOINGPut your intuition to work3 steps
Binary Search
Use the lesson’s examples and explanation to check your idea.
Personal reflection. Nothing is sent to an AI service.GUIDED PRACTICE · 5–10 MINExplain how each comparison narrows a sorted search interval.
Before you start: Array indices and comparisons
Pseudocode: trace the idea, then apply it in the lesson’s language.
values = [2, 5, 8, 12, 16]
target = 12
low = 0
high = 4
mid = floor((low + high) / 2)
Walk through the example
Guided trace, not live execution
low=0 · mid=2 · high=4 → value=8low=3 · mid=3 · high=4 → value=12
8 < 12: discard indices 0–2.
Optional practice. Your grade and code stay unchanged. These answers reset when you leave.Before you start
Browser lesson checks; review each requirement in Tests.
Catalog level: Easy · Estimated time: 15 min. Your prior experience can change the difficulty.
Sample case — your program reads stdin and prints to stdout.
Need a hand?
Start with a small test case. Hints progress from an idea to an explanation and, when requested, code.
Starter Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return -1.
Binary search works by repeatedly dividing the search interval in half.
Example: nums=[−1,0,3,5,9,12], target=9 → index 4
Input format
Line 1: n (array size). Line 2: n space-separated sorted integers. Line 3: target.
Output format
The index of target (0-based), or -1 if not found.
Constraints
1 ≤ n ≤ 10⁴, -10⁴ ≤ nums[i], target ≤ 10⁴