> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/binary-search/744-find-smallest-letter-greater-than-target.md).

# 744    Find Smallest Letter Greater Than Target

## 744. [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/)

## 1. Question

Given a list of sorted characters`letters`containing only lowercase letters, and given a target letter`target`, find the smallest element in the list that is larger than the given target.

Letters also wrap around. For example, if the target is`target = 'z'`and`letters = ['a', 'b']`, the answer is`'a'`.

**Examples:**

```
Input:

letters = ["c", "f", "j"]
target = "a"

Output: "c"


Input:

letters = ["c", "f", "j"]
target = "c"

Output: "f"


Input:

letters = ["c", "f", "j"]
target = "d"

Output: "f"


Input:

letters = ["c", "f", "j"]
target = "g"

Output: "j"


Input:

letters = ["c", "f", "j"]
target = "j"

Output: "c"


Input:

letters = ["c", "f", "j"]
target = "k"

Output: "c"
```

**Note:**

1. `letters`has a length in range`[2, 10000]`.
2. `letters`consists of lowercase letters, and contains at least 2 unique letters.
3. `target`is a lowercase letter.

## 2. Implementation

**(1) Binary Search**

思路: 非常典型的二分查找 找左边界，思路和search insert position是一样的，其中注意题目要求letters是可以wrap around的 (也就是如果target在数组的插入点是在数组末端的时候，则数组的第一个字母为所求解)

```java
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int start = 0, end = letters.length - 1, mid = 0;

        while (start + 1 < end) {
            mid = start + (end - start) / 2;
            if (letters[mid] <= target) {
                start = mid + 1;
            }
            else {
                end = mid;
            }
        }

        if (letters[start] > target) {
            return letters[start];
        }
        else if (letters[end] > target) {
            return letters[end];
        }
        else {
            return letters[0];
        }
    }
}
```

## 3. Time & Space Complexity

Binary Search: 时间复杂度O(logn), 空间复杂度O(1)
