Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Next word

Sharing is caring!

Problem statement
Given a word w, consisting of characters a-z, A-Z and 0-9, compute the next lexicographical word w',
with 0-9 < A-Z < a-z.

ascii-table

Sample Input

hLPk7

Output

hLPk8

Solution

import sys

def nextWord(w):
    word = list(w)
    cursor = len(w) - 1
    carry = True
    while carry and cursor >= 0:
        carry = False
        word[cursor] =  chr(ord(word[cursor]) + 1)
        if ord(word[cursor]) == 58:
            # '9' -> 'A'
            word[cursor] = "A"
        elif ord(word[cursor]) == 91:
            # 'Z' -> 'a'
            word[cursor] = "a"
        elif ord(word[cursor]) == 123:
            # 'z' -> '0'
            if cursor > 0:
                word[cursor] = "0"
                cursor -= 1
                carry = True
            else:
                return None
            
        
    return "".join(word)

word = "k7"
print(nextWord(word))

Notebook file
https://github.com/lucaslouca/coding-problems/tree/master/python/NextWord