Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1
Input
n = 6 nums = [5, 7, 7, 8, 8, 10] target = 8
Output
[3, 4]
Explanation
The target 8 occurs from index 3 through index 4.
Example 2
Input
n = 6 nums = [5, 7, 7, 8, 8, 10] target = 6
Output
[-1, -1]
Explanation
The target 6 does not exist in the array.
Constraints
Hints:
Hint 1
Because the array is sorted, use binary search instead of scanning the entire array.
Hint 2
Perform binary search twice:
- Find the first occurrence of target.
- Find the last occurrence of target.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 22, 2026
Last updated
Aug 22, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output