Binary search (LeetCode)

*For the generic concept of **binary search**, see Binary search.*
LeetCode problem 704. Binary search.

## Problem description

Given a **sorted** (in ascending order) integer array `nums` of `n` elements and a `target` value, write a function to search `target` in `nums`. If `target` exists, then return its index, otherwise return -1.

Example 1

```
**Input:** nums = [-1,0,3,5,9,12], target = 9
**Output:** 4
**Explanation:** 9 exists in nums and its index is 4

```

Example 2

```
**Input:** nums = [-1,0,3,5,9,12], target = 2
**Output:** -1
**Explanation:** 2 does not exist in nums so return -1

```

Note
1. You may assume that all elements in `nums` are unique.
2. `n` will be in the range `[1, 10000]`.
3. The value of each element in `nums` will be in the range `[-9999, 9999]`.

## Analysis

### Trivial cases

* If the array is empty, then return -1.
* If the array has only one element, then return 0 if that element is the target; otherwise return -1.

### General approach

1. Keep a `left` pointer and a `right` pointer.
	* Initialize `left` to 0, and `right` to `array.length - 1`.
2. Find `mid` using
```
int mid = left + (right - left) / 2;

```
 to prevent overflow.
3. Compare target and `array[mid]`.
	* If `target == array[mid]` then return `mid`.
	* If `target < array[mid]` then `right = mid - 1`.
	* Otherwise `left = mid + 1`.
4. Iterate until `left >= right`.
5. If we end up with `left > right`, this means that our search has failed. Return -1 in this case.

### Complexity analysis

#### Time complexity

The time complexity is **O(log *n*)**, since we are squeezing the search interval by one half each time, until the search interval only has a size of 1.

#### Space complexity

Stack
The space complexity on stack is obviously O(1), since we only used a fixed set of helper variables to reduce our search space and to find the result.
Heap
The space complexity on stack is O(1) because we did not allocate any new objects.
So the total space complexity is O(1).

## Solution

### C++

```
class Solution {
public:
 static const int FAIL = -1;

 int search(const vector<int>& nums, const int& target) {
 if (nums.empty()) {
 return FAIL;
 }

 int left = 0, right = nums.size() - 1;
 while (left <= right) {
 int mid = left + (right - left) / 2; // prevent overflow
 if (nums[mid] == target) {
 return mid;
 }
 else if (nums[mid] < target) {
 left = mid + 1;
 }
 else {
 right = mid - 1;
 }
 }
 return FAIL;
 }
};

```

### Java

```
public class Solution {
 public static final int FAIL = -1;

 public int search(int[] array, int target) {
 // Write your solution here
 if ((array == null) || (array.length == 0)) {
 return FAIL;
 }

 int left = 0, right = array.length - 1;
 while (left <= right) {
 int mid = left + (right - left) / 2; // prevent overflow
 if (array[mid] == target) {
 return mid;
 }
 else if (array[mid] < target) {
 left = mid + 1;
 }
 else if (array[mid] > target) {
 right = mid - 1;
 }
 }
 return FAIL;
 }
}

```

## Programming notes

* Use
```
int mid = left + (right - left) / 2;

```
 to prevent overflow.
* Use
```
while (left <= right)

```
 as the while-loop condition to cover the case of only one element in the array.