
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							First and Last Position of Element
								Certification: Basic Level
								Accuracy: 0%
								Submissions: 0
								Points: 5
							
							Write a JavaScript program to find the first and last position of a target element in a sorted array. Given a sorted array of integers and a target value, return the starting and ending position of the target element. 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: 
- The sorted array is [5, 7, 7, 8, 8, 10]. 
 - Target element 8 appears at indices 3 and 4. 
 - First occurrence of 8 is at index 3, last occurrence of 8 is at index 4. 
 - Return [3, 4] as the result.
 
 - The sorted array is [5, 7, 7, 8, 8, 10]. 
 
Example 2
- Input: nums = [5, 7, 7, 8, 8, 10], target = 6
 - Output: [-1, -1]
 - Explanation: 
- The sorted array is [5, 7, 7, 8, 8, 10]. 
 - Target element 6 is searched in the array. 
 - 6 is not present in the array. 
 - Since target is not found, return [-1, -1].
 
 - The sorted array is [5, 7, 7, 8, 8, 10]. 
 
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 achieve O(log n) time complexity
 - Perform two separate binary searches: one for first position, one for last position
 - For finding first position, when target is found, continue searching in left half
 - For finding last position, when target is found, continue searching in right half
 - Handle edge cases where target is not present in the array
 - Return [-1, -1] if target is not found