Applied AI Engineer (LLM) coding learning path Level 2 This level · 29 of 31

Find First and Last Position of Element in Sorted Array

Medium Binary search

Problem

Given a sorted array that may contain duplicates, return the first and last index of a target value, or [-1, -1] if the target is not present. The search should run in O(log n) time.

Original: LeetCode 34: Find First and Last Position of Element in Sorted Array.

Examples

Example 1

Input`nums = [5, 7, 7, 8, 8, 10], target = 8`
Output`[3, 4]`

Example 2

Input`nums = [5, 7, 7, 8, 8, 10], target = 6`
Output`[-1, -1]`

Example 3

Input`nums = [], target = 0`
Output`[-1, -1]`

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is a non-decreasing array.
  • -10^9 <= target <= 10^9

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 34: Find First and Last Position of Element in Sorted Arrayleetcode.com
Previous
Next