Skip to content

๐ŸŒณ Binary search

Medium Analyse ๐Ÿงฉ Logical Reasoning ๐Ÿ’ป Computational Thinking โฑ about 20 minutes 5 tests (2 shown)

Problem

Write binary_search(nums, target) that returns the index of target in the sorted list nums, or -1 if it is not there. Do not scan every element: halve the search range each step.

You will learn: Implement binary search and reason about its O(log n) running time.

Examples

Input: binary_search([1, 3, 5, 7, 9], 7)

Output: 3

Input: binary_search([1, 3, 5], 2)

Output: -1

Hints

โœ“ Verified Submissions are checked against all tests, including hidden ones.

โ–ถ Runs in your browser Run checks the example tests in your browser. Verified grading with hidden tests needs the secure runner, which is not set up yet โ€” submissions are saved as practice, with no score.

Not available yet Code execution for this language is not available yet: the secure code runner has not been set up. You can write and save your code and compare it with the worked solution, but it will not be run.

Loading editorโ€ฆ

Run is unavailable for this language until the secure runner is set up.

Example tests (ran in your browser)

Stuck? Read the failing case carefully, compare the expected and actual values, then try a hint. (AI debugging help is not configured on this server.)