
Sponsored
Sponsored
The goal is to use the binary search algorithm to achieve O(log n) time complexity. We perform two separate binary searches:
Time Complexity: O(log n) due to binary search. Space Complexity: O(1) as no extra space is used apart from input and output.
1#include <stdio.h>
2
3int binarySearchFirst(int* nums, int numsSize, int target) {
4 int left = 0, right = numsSize - 1, result = -1;
5 while (left <= right) {
6 int mid = left + (right - left) / 2;
7 if (nums[mid] >= target) {
8 if (nums[mid] == target) result = mid;
9 right = mid - 1;
10 } else {
11 left = mid + 1;
12 }
13 }
14 return result;
15}
16
17int binarySearchLast(int* nums, int numsSize, int target) {
18 int left = 0, right = numsSize - 1, result = -1;
19 while (left <= right) {
20 int mid = left + (right - left) / 2;
21 if (nums[mid] <= target) {
22 if (nums[mid] == target) result = mid;
23 left = mid + 1;
24 } else {
25 right = mid - 1;
26 }
27 }
28 return result;
29}
30
31void searchRange(int* nums, int numsSize, int target, int* returnSize) {
32 returnSize[0] = binarySearchFirst(nums, numsSize, target);
33 returnSize[1] = binarySearchLast(nums, numsSize, target);
34}
35
36int* findFirstAndLastPosition(int* nums, int numsSize, int target, int* returnSize){
37 int* result = malloc(2 * sizeof(int));
38 result[0] = -1;
39 result[1] = -1;
40 if (numsSize == 0) {
41 return result;
42 }
43 searchRange(nums, numsSize, target, result);
44 return result;
45}
46This solution uses two modified binary searches, one to find the first occurrence of the target and another to find the last occurrence. The code makes sure to continue searching even if the target is found to ensure the first or last position is located.