oneby7

Binary Search Lower and upper bounds

229. Find First and Last Position of Element in Sorted Array

Medium

You are given an array of integers nums, sorted in non-decreasing order, and an integer target. The same value can appear many times in a row.

Return [first, last], where first is the smallest index that holds target and last is the largest. If target does not appear in nums, return [-1,-1]. Indexes start at 0.

Example 1

Input: nums = [-4, 0, 3, 3, 3, 8, 11], target = 3

Output: [2,4]

Explanation: 3 appears at indexes 2, 3 and 4. The first of them is 2 and the last is 4.

Example 2

Input: nums = [7, 7, 7, 7], target = 7

Output: [0,3]

Explanation: Every element is 7, so the answer runs from the first index, 0, to the last, 3.

Example 3

Input: nums = [-10, -6, -6, 1], target = -5

Output: [-1,-1]

Explanation: −5 would sit between −6 and 1, but no element equals it, so both entries are −1.

Check your understanding

Work out the answer for this input before you write any code.

nums = [-3, 0, 4, 4, 4, 9], target = 4

Constraints

  • 0 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums[i] ≤ nums[i + 1] (sorted, repeats allowed)
  • -109 ≤ target ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.