Leetcode 34: Find First and Last Position of Element in Sorted Array

grid47
grid47
Exploring patterns and algorithms
Nov 3, 2024 5 min read

A soft glowing bar where the positions of elements light up in sequence.
Solution to LeetCode 34: Find First and Last Position of Element in Sorted Array Problem

Given a sorted array ’nums’ in non-decreasing order, find the starting and ending index of a target value. If the target is not found, return [-1, -1]. Your solution must run in O(log n) time complexity.
Problem
Approach
Steps
Complexity
Input: The input is a sorted array 'nums' and a target value that needs to be searched.
Example: nums = [1, 2, 3, 3, 3, 5, 6, 7], target = 3
Constraints:
• 0 <= nums.length <= 10^5
• -10^9 <= nums[i] <= 10^9
• nums is sorted in non-decreasing order.
• -10^9 <= target <= 10^9
Output: The output should be an array of two integers, representing the starting and ending position of the target value, or [-1, -1] if the target is not found.
Example: For nums = [1, 2, 3, 3, 3, 5, 6, 7], target = 3, the output is [2, 4].
Constraints:
Goal: To find the starting and ending positions of the target in a sorted array efficiently.
Steps:
• Use binary search to find the first occurrence of the target value (lower bound).
• Use binary search to find the position just after the last occurrence of the target value (upper bound).
• Return the index range or [-1, -1] if the target is not found.
Goal: The solution should work within the given constraints and time complexity.
Steps:
• The array can have up to 10^5 elements.
• The target value can be any integer between -10^9 and 10^9.
Assumptions:
• The array is sorted and can contain duplicate values.
Input: nums = [1, 2, 3, 3, 3, 5, 6, 7], target = 3
Explanation: The target value 3 appears three times in the array. The starting position is 2, and the ending position is 4.

Input: nums = [1, 2, 3, 3, 3, 5, 6, 7], target = 0
Explanation: The target value 0 is not present in the array, so the output is [-1, -1].

Input: nums = [], target = 5
Explanation: The array is empty, so the target cannot be found, resulting in [-1, -1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus