Find a string such that every character is lexicographically greater than its immediate next character in Python

Sometimes we need to create a string where each character is lexicographically greater than its immediate next character. This creates a strictly decreasing sequence of characters from left to right.

Given a number n, we need to generate a lowercase string of length n+1 where each character is lexicographically larger than the character that follows it.

Example

If the input is n = 15, the output will be "ponmlkjihgfedcba" (16 characters total).

Algorithm

To solve this problem, we follow these steps ?

  • Calculate extra = n % 26 to find remaining characters after full alphabet cycles
  • If extra >= 1, add characters from the reverse alphabet starting at position 26 - (extra + 1)
  • Calculate count = n // 26 to find how many complete alphabet cycles we need
  • For each complete cycle, append the entire reverse alphabet

Implementation

def show_string(n, alphabet):
    temp_str = ""
    extra = n % 26
    
    if extra >= 1:
        for i in range(26 - (extra + 1), 26):
            temp_str += alphabet[i]
    
    count = n // 26
    for i in range(1, count + 1):
        for j in range(26):
            temp_str += alphabet[j]
    
    return temp_str

n = 15
reverse_alphabet = "zyxwvutsrqponmlkjihgfedcba"
result = show_string(n, reverse_alphabet)
print(f"Input: {n}")
print(f"Output: {result}")
print(f"Length: {len(result)}")
Input: 15
Output: ponmlkjihgfedcba
Length: 16

How It Works

The algorithm uses a reverse alphabet string "zyxwvutsrqponmlkjihgfedcba" where 'z' is at index 0 and 'a' is at index 25. By selecting characters from this string in order, we ensure each character is lexicographically greater than the next.

For n = 15:

  • extra = 15 % 26 = 15
  • Start from index 26 - (15 + 1) = 10, which gives us "ponmlkjihgfedcba"
  • count = 15 // 26 = 0, so no complete cycles are added

Alternative Approach

Here's a simpler approach that directly generates the decreasing sequence ?

def generate_decreasing_string(n):
    result = ""
    start_char = ord('z')
    
    for i in range(n + 1):
        char_code = start_char - (i % 26)
        if char_code < ord('a'):
            char_code = ord('z')
        result += chr(char_code)
    
    return result

n = 15
result = generate_decreasing_string(n)
print(f"Input: {n}")
print(f"Output: {result}")
print(f"Length: {len(result)}")
Output: ponmlkjihgfedcba
Length: 16

Conclusion

To create a lexicographically decreasing string, use a reverse alphabet and calculate the starting position based on the required length. The modulo operation helps handle cases where the string length exceeds 26 characters.

Updated on: 2026-03-25T09:10:51+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements