⌘K
Flycodx

Binary Search

Binary Search

EasyBinary Search42% accepted

Given a sorted array of n distinct integers in non-decreasing order and a target value, find the index of the target using binary search. Return the 0-based index, or -1 if the target is not present. Your solution must run in O(log n) time. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=6, target=7, array=[1 3 5 7 9 11] → 3

Input format — only if your code reads from stdin

Input format (stdin): - First line: two integers n (array size) and target - Second line: n space-separated sorted integers Output: the 0-based index of the target, or -1.

Approach

Set low=0, high=n-1. Each iteration compute mid = (low+high)/2. If arr[mid] < target, narrow to right half (low=mid+1). If arr[mid] > target, narrow to left (high=mid-1). If equal, return mid. Loop exits when low>high.

Input

6 7 1 3 5 7 9 11

Output

3
  • •1 ≤ n ≤ 10^5, -10^9 ≤ elements, target ≤ 10^9, all elements are distinct
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3