← Microsoft bank

Microsoft · Question 46 · Binary Search

Binary Search

Binary SearchJavacode⏱ O(logn)💾 O(1)
Product-based

Problem

Given a sorted array and a target value, return the index if found, else -1.

Approach

Halve the search range by comparing the middle.

Time O(logn)Space O(1)

How it works

  1. 1Compare the middle element.
  2. 2Discard the half that cannot hold the target.

Sample input / output

Input:
6
-1 0 3 5 9 12
9
Output:
4

Constraints

1 <= nums.length <= 10^4; sorted distinct; -10^4 <= target <= 10^4.

Solution — read it, then walk it

Time O(logn)Space O(1)Loops 2Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intsearch(int[] nums, inttarget)DEFINE left = 0, right =nums.length - 1while (left <= right)DEFINE mid = left + (right- left) / 2if (nums[mid] ==target) return midelse if (nums[mid] <target) left = mid + 1ELSERETURN -1DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt()DEFINE [] nums = new int[n]for (int i = 0; i <nums.length; i++)nums[i] = sc.nextInt()DEFINE target =sc.nextInt()System.out.println(search(nums,target))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/18

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits