Educatifu
Open menu

Binary Search

Mediumarrayssearching

Find the position of a target value in a sorted array, using an efficient search.

Input

The first line contains an integer n. The second line contains n distinct integers in strictly increasing order. The third line contains the integer target.

Output

The 0-based index of target in the array, or -1 if it is not present.

Examples

Example 1

Input
5
1 3 5 7 9
7
Output
3

7 is at index 3 (0-based).

Example 2

Input
5
1 3 5 7 9
4
Output
-1

4 is not in the array, so -1.

Example 3

Input
1
42
42
Output
0

Single element at index 0.

Constraints

  • 1 <= n <= 10^5
  • The array is sorted in strictly increasing order.
  • -10^9 <= values, target <= 10^9

Hints

Reveal hint 1

The array is sorted — you do not need to look at every element. Halve the search range each step.

Reveal hint 2

Keep a low and high bound. Compare the middle element to the target and discard the half that cannot contain it.

Reference solution (spoiler — try it yourself first)

Approach

Binary search: maintain [lo, hi]. Compare arr[mid] to target; move lo or hi to discard half the range each step until found or the range is empty.

import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
arr = data[1:1 + n]
target = data[1 + n]
lo, hi, ans = 0, n - 1, -1
while lo <= hi:
    mid = (lo + hi) // 2
    if arr[mid] == target:
        ans = mid
        break
    elif arr[mid] < target:
        lo = mid + 1
    else:
        hi = mid - 1
print(ans)

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation