Isaac Emmanuel
09 Sept 2026•EasyGo / Python / TypeScript

Find Smallest Letter Greater Than Target

Find the smallest sorted letter strictly greater than a target, wrapping to the first letter when necessary.

Use upper-bound binary search for the first value greater than the target, then wrap the resulting index modulo the array length.

Complexity

O(log n) time and O(1) extra space.

Solution files

Go•find-smallest-letter-greater-than-target/solution.go
package main

import "sort"

func nextGreatestLetter(letters []byte, target byte) byte {
	index := sort.Search(len(letters), func(index int) bool { return letters[index] > target })
	return letters[index%len(letters)]
}
Python•find-smallest-letter-greater-than-target/solution.py
from bisect import bisect_right


class Solution:
    def nextGreatestLetter(self, letters: list[str], target: str) -> str:
        return letters[bisect_right(letters, target) % len(letters)]
TypeScript•find-smallest-letter-greater-than-target/solution.ts
function nextGreatestLetter(letters: string[], target: string): string {
  let left = 0;
  let right = letters.length;
  while (left < right) { const middle = left + Math.floor((right - left) / 2); if (letters[middle] <= target) left = middle + 1; else right = middle; }
  return letters[left % letters.length];
}