LeetCode Solutions

744. Find Smallest Letter Greater Than Target

Time: $O(\log n)$

Space: $O(1)$

			

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()];
  }
};
			

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];
  }
}
			

class Solution:
  def nextGreatestLetter(self, letters: List[str], target: str) -> str:
    l = 0
    r = len(letters)

    while l < r:
      m = (l + r) >> 1
      if letters[m] <= target:
        l = m + 1
      else:
        r = m

    return letters[l % len(letters)]