Ninja technique🥷 to ACE DSA Interviews.
class Solution {
private:
int firstOccurrence(vector<int>& nums, int target)
{
int n = nums.size();
int l = 0, r = n - 1;
int ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) {
r = mid - 1;
ans = mid;
} else if (nums[mid] > target)
r = mid - 1;
else
l = mid + 1;
}
return ans;
}
int lastOccurrence(vector<int>& nums, int target)
{
int n = nums.size();
int l = 0, r = n - 1;
int ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) {
l = mid + 1;
ans = mid;
} else if (nums[mid] > target)
r = mid - 1;
else
l = mid + 1;
}
return ans;
}
public:
vector<int> searchRange(vector<int>& nums, int target)
{
int first = firstOccurrence(nums, target);
int last = lastOccurrence(nums, target);
return vector<int> { first, last };
}
};