# 34. Find First and Last Position of Element in Sorted Array

## LeetCode [34. Find First and Last Position of Element in Sorted Array](https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/)

### Description

Given an array of integers `nums` sorted in ascending order, find the starting and ending position of a given `target` value.

If `target` is not found in the array, return `[-1, -1]`.

**Follow up:** Could you write an algorithm with `O(log n)` runtime complexity?

**Example 1:**

```
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
```

**Example 2:**

```
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
```

**Example 3:**

```
Input: nums = [], target = 0
Output: [-1,-1]
```

**Constraints:**

* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`

### Tags

Array, Binary Search

### Solution

Based on the binary search template, we need to re-design the case of `nums[mid] == target`, because we do not want to return the found index immediately when it might not be either the starting or the ending position. In the case of equality of the both, if we need to find the starting position of `target`, we assign `mid` to `r`. Otherwise we assign mid to `l`. After the loop, If we are looking for the starting position, we check the `nums[l]` first and then `nums[r]`, otherwise the process is reversed. Return `-1` when `target` does not present in the array.

### Complexity

* Time complexity: $$O(log(n))$$
* Space complexity: $$O(1)$$

### Code

```go
func searchRange(nums []int, target int) []int {
	if len(nums) == 0 {
		return []int{-1, -1}
	}
	return []int{binarySearch(nums, target, true), binarySearch(nums, target, false)}
}

func binarySearch(nums []int, target int, first bool) int {
	l, r := 0, len(nums)-1
	for l+1 < r {
		mid := l + (r-l)/2
		if nums[mid] > target {
			r = mid
		} else if nums[mid] < target {
			l = mid
		} else {
			if first {
				r = mid
			} else {
				l = mid
			}
		}
	}
	if !first {
		l, r = r, l
	}
	if nums[l] == target {
		return l
	}
	if nums[r] == target {
		return r
	}
	return -1
}
```
