← Microsoft bank

Microsoft · Question 47 · Binary Search

Search Insert Position

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

Problem

Find the index where target should be inserted to maintain sorted order.

Approach

Binary search; the loop exit point is the insertion index.

Time O(logn)Space O(1)

How it works

  1. 1Standard binary search for the target.
  2. 2A miss leaves left at the insertion point.

Sample input / output

Input:
4
1 3 5 6
5
Output:
2

Constraints

1 <= nums.length <= 10^4; distinct sorted; 1 <= 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 intsearchInsert(int[] nums,int target)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 leftDEFINE 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(searchInsert(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