
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.
1class Solution {
2 public int[] searchRange(int[] nums, int target) {
3 int[] result = new int[]{-1, -1};
4 if (nums.length == 0) return result;
5 result[0] = findFirst(nums, target);
6 result[1] = findLast(nums, target);
7 return result;
8 }
9
10 private int findFirst(int[] nums, int target) {
11 int left = 0, right = nums.length - 1, result = -1;
12 while (left <= right) {
13 int mid = left + (right - left) / 2;
14 if (nums[mid] >= target) {
15 if (nums[mid] == target) result = mid;
16 right = mid - 1;
17 } else {
18 left = mid + 1;
19 }
20 }
21 return result;
22 }
23
24 private int findLast(int[] nums, int target) {
25 int left = 0, right = nums.length - 1, result = -1;
26 while (left <= right) {
27 int mid = left + (right - left) / 2;
28 if (nums[mid] <= target) {
29 if (nums[mid] == target) result = mid;
30 left = mid + 1;
31 } else {
32 right = mid - 1;
33 }
34 }
35 return result;
36 }
37}This Java solution implements the same logic as other languages: two binary search functions to find the first and last occurrences of the target, returning their indices.