Back to track
#17 Easy Foundations

Binary Search

Open the editor

Problem

Find target in sorted array.

Constraints

1 <= N <= 200000
Array is sorted

Hints

  1. 1

    Low/high pointers

  2. 2

    Mid calculation

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; long long target;
  cin >> n >> target;
  vector<long long> a(n);
  for (int i = 0; i < n; i++) cin >> a[i];
  int l = 0, r = n - 1;
  while (l <= r) {
    int m = l + (r - l) / 2;
    if (a[m] == target) { cout << m << '\n'; return 0; }
    if (a[m] < target) l = m + 1; else r = m - 1;
  }
  cout << -1 << '\n';
  return 0;
}

© 2026 ChitChat