18 · Binary Search

#34 Find First and Last Position of Element in Sorted Array

Mediumsolve on LeetCode ↗

frequently reported atMetaLinkedInAppleBloombergAmazonMicrosoft

the problem

In plain words

Given a sorted array (duplicates allowed), return [first, last] index of target, or [-1, -1] if absent. Must be O(log n).

in nums = [5,7,7,8,8,10], target = 8

out [3,4]

in nums = [5,7,7,8,8,10], target = 6

out [-1,-1]

in nums = [], target = 0

out [-1,-1]

  • 0 ≤ n ≤ 10⁵
  • -10⁹ ≤ nums[i], target ≤ 10⁹
  • Sorted non-decreasing

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #35
      Search Insert Position
      Easyin Binary Search
    2. #278
      First Bad Version
      Easyin Binary Search