Coder's Cat

2020-02-03

## Challenge Description

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

Your algorithm’s runtime complexity must be in the order of O(log n).

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

Example 1:

Example 2:

## Naive Solution

Linear scan array from left to right or from right to left.

Find the first index with given value. A trivial optimization here is when we find current element is greater than target(search left to right), we won’t search the left elements.

Time complexity: $O(N)$

Naive approach will not meet the challenge requirement. We can use the approach of binary search, but it’s a variant of original binary-search.

Take search first left position for example, When we got an index(suppose idx) where value equal target, we store the current position and safely ignore the right part [idx ~ ..] of the array, so we update the hi pivot.

Search last right position is similar.

Time complexity: $O(logN)$.

Preparing for an interview? Check out this!