Skip to content

744. Find Smallest Letter Greater Than Target

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  char nextGreatestLetter(vector<char>& letters, char target) {
    int l = 0;
    int r = letters.size();

    while (l < r) {
      const int m = (l + r) / 2;
      if (letters[m] > target)
        r = m;
      else
        l = m + 1;
    }

    return letters[l % letters.size()];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public char nextGreatestLetter(char[] letters, char target) {
    int l = 0;
    int r = letters.length;

    while (l < r) {
      final int m = (l + r) / 2;
      if (letters[m] > target)
        r = m;
      else
        l = m + 1;
    }

    return letters[l % letters.length];
  }
}
1
2
3
4
5
class Solution:
  def nextGreatestLetter(self, letters: list[str], target: str) -> str:
    l = bisect.bisect_right(range(len(letters)), target,
                            key=lambda m: letters[m])
    return letters[l % len(letters)]