
Problem
Solution
Submissions
Search for a Range
Certification: Intermediate Level
Accuracy: 0%
Submissions: 8
Points: 10
Write a C program to find the first and last position of a given target value in a sorted array. If the target is not found in the array, return [-1, -1]. The algorithm must run in O(log n) time complexity.
Example 1
- Input: nums = [5, 7, 7, 8, 8, 10], target = 8
- Output: [3, 4]
- Explanation:
- Step 1: The target value 8 appears at indices 3 and 4.
- Step 2: First occurrence is at index 3.
- Step 3: Last occurrence is at index 4.
- Step 4: Therefore, return [3, 4].
- Step 1: The target value 8 appears at indices 3 and 4.
Example 2
- Input: nums = [5, 7, 7, 8, 8, 10], target = 6
- Output: [-1, -1]
- Explanation:
- Step 1: The target value 6 is not present in the array.
- Step 2: Since target is not found, return [-1, -1].
- Step 3: This indicates that the target has no first or last position.
- Step 1: The target value 6 is not present in the array.
Constraints
- 0 ≤ nums.length ≤ 10^5
- -10^9 ≤ nums[i] ≤ 10^9
- nums is a non-decreasing array
- -10^9 ≤ target ≤ 10^9
- Time Complexity: O(log n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use binary search to find the first occurrence of the target.
- Use binary search to find the last occurrence of the target.
- Modify the standard binary search to find leftmost position.
- Modify the standard binary search to find rightmost position.
- Return [-1, -1] if target is not found in either search.