---
# System prepended metadata

title: 34-Find First and Last Position of Element in Sorted Array
tags: [Medium]

---

#  34-Find First and Last Position of Element in Sorted Array
###### tags: `Medium`
## Question
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
## Key
## Reference
https://medium.com/@bill800227/leetcode-34-find-first-and-last-position-of-element-in-sorted-array-685f56603596
## Solution
```cpp=
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int idx1 = lower_bound(nums, target);
        int idx2 = lower_bound(nums, target+1)-1;
        if (idx1 <= idx2)
            return {idx1, idx2};
        else
            return {-1, -1};
    }
private:
    int lower_bound(vector<int>& nums, int target) {
        int l = 0, r = nums.size()-1;
        while (l <= r) {
            int mid = (r+l)/2;
            if (nums[mid] < target)
                l = mid+1;
            else
                r = mid-1;
        }
        return l;
    }
};
```