Ctrl K

Next Letter, Wrapping Around

Easy
Storage bins carry letter labels, and the list labels is sorted alphabetically (letters may repeat, but there are at least two distinct ones). You are also given a letter after. Return the smallest letter in labels that comes strictly after after in the alphabet. If there is none, wrap around and return the first letter of the list. The list is already sorted; try to beat a linear scan.
Example 1
labels=['b', 'e', 'e', 'k', 'q'], after='e' → 'k'

"e" itself does not count, the letter must be strictly greater. The next one is "k".

Example 2
labels=['d', 'h', 'm'], after='a' → 'd'

Every letter is greater than "a", and the smallest of them is "d".

Example 3
labels=['c', 'c', 'w'], after='y' → 'c'

Nothing is greater than "y", so we wrap around and return the first letter, "c".

Constraints
  • 2 ≤ len(labels) ≤ 10⁴
  • labels[i] and after are lowercase English letters
  • labels is sorted in non-decreasing order
  • labels contains at least two distinct letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSlot on a Sorted Shelf EasyThe Lost Ticket EasyValues in Both Lists EasyShared Values With Repeats EasyFind in a Sorted List Easy
loading Python…
Input
labels=['b', 'e', 'e', 'k', 'q'], after='e'
Expected
'k'

Run checks the first 3 tests in your browser. Submit checks all 80 tests on the server, hidden ones included.