Community Problem

Find Smallest Letter Greater Than Target

Difficulty: Easy

Classic upper_bound on a sorted character array, with a wrap-around twist that makes the binary-search invariants worth thinking through carefully.

Find Smallest Letter Greater Than Target

Classic upper_bound on a sorted character array, with a wrap-around twist that makes the binary-search invariants worth thinking through carefully.

EASY
Free
binary-search
arrays

By CodeSnatch

March 27, 2026

·

Updated May 18, 2026

761 views

10

4.6 (13)

Picked this for the EASY-tier official Cat 4 entry because off-by-one bugs in upper_bound are the single most common mistake I see in real onsites, and the wrap-around twist forces you to be honest about whether your invariant covers the not-found case. The half-open [lo, hi) template is the version that survives senior interviews unscathed.

Find Smallest Letter Greater Than Target

Given a sorted (non-decreasing) array of lowercase characters letters and a target lowercase character target, return the smallest character in letters that is strictly greater than target. Duplicates are allowed in letters. The comparison wraps around: if every character in letters is <= target, the answer is letters[0].

Examples

Example 1:

  • Input: letters = ['c', 'f', 'j'], target = 'a'
  • Output: 'c'
  • Explanation: 'c' is the smallest letter strictly greater than 'a'.

Example 2:

  • Input: letters = ['c', 'f', 'j'], target = 'c'
  • Output: 'f'
  • Explanation: 'c' is not strictly greater than 'c', so we skip to the next.

Example 3:

  • Input: letters = ['c', 'f', 'j'], target = 'j'
  • Output: 'c'
  • Explanation: No character in letters is greater than 'j', so wrap to letters[0].

Example 4:

  • Input: letters = ['x', 'x', 'y', 'y'], target = 'z'
  • Output: 'x'
  • Explanation: All letters are <= 'z', wrap to the first.

Constraints

  • 2 <= letters.length <= 10^4
  • letters[i] is a lowercase English letter.
  • letters is sorted in non-decreasing order.
  • letters contains at least two distinct letters.
  • target is a lowercase English letter.

Follow-up

Which binary-search template handles the wrap-around case most cleanly: equality lo <= hi with explicit not-found handling, or the half-open [lo, hi) upper_bound that returns hi when nothing qualifies?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems