
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.
1public class Solution {
2 public int[] SearchRange(int[] nums, int target) {
3 return new int[] {FindFirst(nums, target), FindLast(nums, target)};
4 }
5
6 private int FindFirst(int[] nums, int target) {
7 int left = 0, right = nums.Length - 1, result = -1;
8 while (left <= right) {
9 int mid = left + (right - left) / 2;
10 if (nums[mid] >= target) {
11 if (nums[mid] == target) result = mid;
12 right = mid - 1;
13 } else {
14 left = mid + 1;
15 }
16 }
17 return result;
18 }
19
20 private int FindLast(int[] nums, int target) {
21 int left = 0, right = nums.Length - 1, result = -1;
22 while (left <= right) {
23 int mid = left + (right - left) / 2;
24 if (nums[mid] <= target) {
25 if (nums[mid] == target) result = mid;
26 left = mid + 1;
27 } else {
28 right = mid - 1;
29 }
30 }
31 return result;
32 }
33}The C# solution uses helper methods for determining the first and last positions through binary search, ensuring proper sorting constraints.