This problem looks busy at first, but the accepted solution is built around one steady invariant. For 34. Find First and Last Position of Element in Sorted Array, the solution in this repository is mainly a binary search solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: binary search, two pointers, sliding window.
The notes already sitting in the source point us in the right direction:
- binary search
- time: O(logN), space: O(1)
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are searchRange.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(logN), space: O(1)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//binary search
02//Runtime: 16 ms, faster than 90.01% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
03//Memory Usage: 14.1 MB, less than 10.23% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
04//time: O(logN), space: O(1)
05class Solution {
06public:
07 vector<int> searchRange(vector<int>& nums, int target) {
08 int n = nums.size();
09
10 if(n == 0) return {-1, -1};
11
12 int left = 0, right = n-1;
13
14 //find left boundary
15 while(left <= right){
16 int mid = (left+right) >> 1;
17 // cout << left << ", " << mid << ", " << right << endl;
18
19 if(nums[mid] < target){
20 left = mid+1;
21 }else{
22 right = mid-1;
23 }
24 }
25
26 if(left >= n || nums[left] != target){
27 return {-1, -1};
28 }
29
30 vector<int> ans = {left};
31
32 //find right boundary
33 left = 0;
34 right = n-1;
35 while(left <= right){
36 int mid = (left+right) >> 1;
37 // cout << left << ", " << mid << ", " << right << endl;
38
39 if(nums[mid] > target){
40 right = mid-1;
41 }else{
42 left = mid+1;
43 }
44 }
45
46 ans.push_back(right);
47
48 return ans;
49 }
50};
Cost