
Problem
Solution
Submissions
First and Last Position in Sorted Array
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a Java program to find the first and last position of a given target value in a sorted array of integers. If the target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Example 1
- Input: nums = [5,7,7,8,8,10], target = 8
- Output: [3, 4]
- Explanation:
- Step 1: Use binary search to find the first occurrence of the target value.
- Step 2: When found, continue searching in the left subarray to find the leftmost position.
- Step 3: Use another binary search to find the last occurrence of the target value.
- Step 4: When found, continue searching in the right subarray to find the rightmost position.
- Step 5: For target 8, the first position is at index 3 and the last position is at index 4.
Example 2
- Input: nums = [5,7,7,8,8,10], target = 6
- Output: [-1, -1]
- Explanation:
- Step 1: Apply binary search to find the target value 6.
- Step 2: After the binary search completes, determine that 6 does not exist in the array.
- Step 3: Since the target is not found, we cannot determine first or last positions.
- Step 4: Return [-1, -1] to indicate the target 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 twice: once to find the first occurrence and once to find the last occurrence
- For finding the first occurrence, when the middle element equals the target, check if it's the first element or if the previous element is different
- For finding the last occurrence, when the middle element equals the target, check if it's the last element or if the next element is different
- Modify the binary search to handle the case where the target doesn't exist in the array
- Be careful with the boundary conditions during binary search