Find Smallest Letter Greater Than Target - Problem

You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.

Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.

Input & Output

Example 1 — Basic Case
$ Input: letters = ["c","f","j"], target = "a"
Output: c
💡 Note: The smallest character greater than 'a' is 'c'
Example 2 — Target in Middle
$ Input: letters = ["c","f","j"], target = "c"
Output: f
💡 Note: The smallest character greater than 'c' is 'f'
Example 3 — Wrap Around
$ Input: letters = ["c","f","j"], target = "z"
Output: c
💡 Note: No character greater than 'z', so return 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
Find Smallest Letter Greater Than Target INPUT letters array (sorted) "c" idx: 0 "f" idx: 1 "j" idx: 2 target "a" Input Values: letters = ["c","f","j"] target = "a" Find smallest char > "a" ALGORITHM STEPS 1 Binary Search Setup left=0, right=2 2 Check mid = 1 "f" > "a"? YES right = mid = 1 3 Check mid = 0 "c" > "a"? YES right = mid = 0 4 Loop Ends left(1) > right(0) Return letters[0] Search Progress [c] [f] [j] Initial [c] [f] After step 2 [c] Found! FINAL RESULT Smallest letter > "a" "c" Output: "c" Verification: * "c" > "a" [OK] * "c" is smallest such char in array Time: O(log n) Key Insight: Binary search finds the first element greater than target in O(log n). Since the array is sorted, we narrow the search by half each iteration. If no element is greater, the array wraps around to return the first element (circular property). TutorialsPoint - Find Smallest Letter Greater Than Target | Optimal Solution (Binary Search)
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
18.5K Views
Medium Frequency
~15 min Avg. Time
892 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