Binary Search
Binary Search
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
Output
- •
1 ≤ n ≤ 10^5, -10^9 ≤ elements, target ≤ 10^9, all elements are distinct
More Binary Search problems
Browse all coding problems →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