Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

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

MediumDay 17 of 60Binary Search

Given an array nums sorted in non-decreasing order (duplicates allowed) and a value target, return the first and last index where target appears, as [first, last]. If target is missing, return [-1, -1]. The solution must run in O(log n).

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], target <= 10^9
  • `nums` is sorted in non-decreasing order
Hints
Frequently asked at: Meta, Amazon, Microsoft, LinkedIn, Goldman Sachs
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min