Ctrl K

Next Palindrome-Free String

Hard
Call a string **tidy** if it uses only the first letters letters of the English alphabet and contains no palindrome of length 2 or more as a run of consecutive characters (so no two neighbouring letters match, and no two letters one apart match either). You are given a tidy string word. Find the lexicographically smallest tidy string of the same length that is strictly greater than word. If there is none, return an empty string. Of two strings of equal length, the greater one has the later letter at the first position where they differ.
Example 1
word="abcd", letters=4 → 'abda'

The final d cannot grow. The third letter c can become d, which differs from both b and a before it. The last position then takes the smallest allowed letter, a, giving abda.

Example 2
word="dcb", letters=4 → ''

The final b could only become c or d, and both already sit within two places of it. The c could only become d, its neighbour. The leading d is already the top letter. No answer exists, so return an empty string.

Example 3
word="bad", letters=6 → 'bae'

Changing the final d to e is enough.

Constraints
  • 1 ≤ len(word) ≤ 10⁵
  • 4 ≤ letters ≤ 26
  • word is tidy
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDoes the Text Fit the Pattern HardEqual Letters Kept Apart HardHarden the Password HardDistinct Word Shorthands HardMirror Chunk Split Hard
loading Python…
Input
word="abcd", letters=4
Expected
'abda'

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