← Microsoft bank

Microsoft · Question 50 · Binary Search

Find First and Last Position of Element in Sorted Array

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

Problem

Return the first and last index of the target value.

Approach

Two biased binary searches: one leans left, one leans right.

Time O(logn)Space O(1)

How it works

  1. 1On a hit, keep searching the biased side.
  2. 2Two passes give first and last positions.

Sample input / output

Input:
6
5 7 7 8 8 10
8
Output:
[3, 4]

Constraints

0 <= nums.length <= 10^5; sorted non-decreasing.

Solution — read it, then walk it

Time O(logn)Space O(1)Loops 2Branches 5Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]searchRange(int[] nums, inttarget)DEFINE [] res = {-1, -1}res[0] = findBound(nums,target, true)res[1] = findBound(nums,target, false)RETURN resDEFINE static intfindBound(int[] nums, inttarget, boolean isFirst)DEFINE left = 0, right =nums.length - 1, result =-1while (left <= right)DEFINE mid = left + (right- left) / 2if (nums[mid] ==target)result = midif (isFirst) right =mid - 1ELSEelse if (nums[mid] <target) left = mid + 1ELSERETURN resultDEFINE 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(Arrays.toString(searchRange(nums,target)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/26

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