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
Output: The smallest character lexicographically greater than
Example: Given
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 targetOutput: The smallest character lexicographically greater than
target, or the first character if none existsExample: 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code