Find Smallest Letter Greater Than Target - Problem
Find the Next Letter in a Sorted Character Array

You're given a sorted array of lowercase letters and a target character. Your mission is to find the smallest character that comes after your target in alphabetical order.

Here's the catch: if no character exists that's greater than your target, you should wrap around and return the first character in the array - think of it as a circular alphabet!

Input: A sorted array letters and a target character target
Output: The smallest character lexicographically greater than target, or the first character if none exists

Example: Given letters = ['c', 'f', 'j'] and target = 'a', return 'c' (first letter greater than 'a')

Input & Output

example_1.py โ€” Basic Case
$ Input: letters = ['c', 'f', 'j'], target = 'a'
โ€บ Output: 'c'
๐Ÿ’ก Note: The smallest character that is lexicographically greater than 'a' is 'c'.
example_2.py โ€” Middle Target
$ Input: letters = ['c', 'f', 'j'], target = 'd'
โ€บ Output: 'f'
๐Ÿ’ก Note: The smallest character that is lexicographically greater than 'd' is 'f'.
example_3.py โ€” Wrap Around Case
$ Input: letters = ['c', 'f', 'j'], target = 'k'
โ€บ Output: 'c'
๐Ÿ’ก Note: Since no character is greater than 'k', we wrap around and return the first character 'c'.

Constraints

  • 2 <= letters.length <= 104
  • letters[i] is a lowercase English letter
  • letters is sorted in non-decreasing order
  • letters contains at least two different characters
  • target is a lowercase English letter

Visualization

Tap to expand
Circular Letter ArrayLetters: ['c', 'f', 'j'] Target: 'd''c''f''j''d'targetNext letter clockwiseAlgorithm Steps:1. Target 'd' between 'c' and 'f'2. Next clockwise letter is 'f'3. Return 'f' as answer
Understanding the Visualization
1
Visualize the Circle
Imagine letters arranged in a circular pattern
2
Find Target Position
Locate where our target would fit in this circle
3
Move Clockwise
Find the next letter in clockwise direction
4
Wrap if Needed
If we reach the end, wrap around to the beginning
Key Takeaway
๐ŸŽฏ Key Insight: The circular nature combined with the sorted property allows us to use binary search for O(log n) efficiency instead of O(n) linear search.
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
67.5K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen