# Search for a Range

## Improved binary search

There is no guarantee which one will be found when using a binary search and the input array has many same elements.

What we need to do is after we got the index, search the left and right to expand the range.

```
if found
left = index
right = index
expand left while A[left] == target
expand right while A[right] == target
```

### Source code *Read on Github*

```
1 public class Solution {
2 public int[] searchRange(int[] A, int target) {
3
4 int s = 0, e = A.length;
5
6 while( s < e ){
7 int mid = (s + e) / 2;
8
9 if(A[mid] == target){
10
11 int _s = mid, _e = mid;
12
13 while(_s - 1 >= 0 && A[_s - 1] == target) _s--;
14 while(_e + 1 < A.length && A[_e + 1] == target) _e++;
15
16 return new int[]{_s, _e};
17
18 }else if(A[mid] < target){
19 s = mid + 1;
20 }else if(A[mid] > target){
21 e = mid;
22 }
23
24 }
25
26 return new int[]{-1, -1};
27
28 }
29 }
```