Program to find lexicographically smallest lowercase string of length k and distance n in Python

Suppose we have two numbers n and k. We have to find the lexicographically smallest lowercase string of size k and distance n. The distance is the sum of the letter number in alphabet. For example, 'a' has letter number 1, 'b' has 2, 'y' has 25, 'z' has 26 and so on.

So, if the input is like n = 15 k = 3, then the output will be "aam", because "aam" is the lexicographically smallest string of length 3 whose distance is 1 + 1 + 13 = 15.

Algorithm

To solve this, we will follow these steps ?

  • Create an array dist of size k, and fill with 1 (representing 'a' for each position)
  • Calculate credit := n - k (remaining distance to distribute)
  • Start from the rightmost position (i := k - 1)
  • While credit > 0, do:
    • val := minimum of credit and 25 (maximum we can add to make 'z')
    • dist[i] := dist[i] + val
    • credit := credit - val
    • i := i - 1
  • Convert each number in dist to corresponding character and join them

Example

Let us see the following implementation to get better understanding ?

def solve(n, k):
    # Initialize with all 'a' characters (value 1 each)
    dist = [1] * k
    
    # Calculate remaining distance to distribute
    credit = n - k
    
    # Start from rightmost position for lexicographically smallest result
    i = k - 1
    while credit > 0:
        # Maximum we can add is 25 (to make 'z' from 'a')
        val = min(credit, 25)
        dist[i] += val
        credit -= val
        i -= 1
    
    # Convert numbers to characters and join
    return "".join(chr(d - 1 + ord("a")) for d in dist)

# Test the function
n = 15
k = 3
result = solve(n, k)
print(f"Input: n={n}, k={k}")
print(f"Output: {result}")

# Verify the distance
distance = sum(ord(c) - ord('a') + 1 for c in result)
print(f"Distance verification: {distance}")
Input: n=15, k=3
Output: aam
Distance verification: 15

How It Works

The algorithm works by starting with the smallest possible string (all 'a's) and then distributing the remaining distance from right to left. This ensures lexicographical minimality because we keep the leftmost characters as small as possible.

For n=15, k=3:

  • Start with ['a', 'a', 'a'] (distance = 3)
  • Need to add 12 more to reach 15
  • Add 12 to rightmost position: 'a' + 12 = 'm'
  • Result: "aam"

Another Example

def solve(n, k):
    dist = [1] * k
    credit = n - k
    
    i = k - 1
    while credit > 0:
        val = min(credit, 25)
        dist[i] += val
        credit -= val
        i -= 1
    
    return "".join(chr(d - 1 + ord("a")) for d in dist)

# Test with different values
test_cases = [(30, 4), (52, 2), (10, 5)]

for n, k in test_cases:
    result = solve(n, k)
    distance = sum(ord(c) - ord('a') + 1 for c in result)
    print(f"n={n}, k={k} ? '{result}' (distance: {distance})")
n=30, k=4 ? aaaz (distance: 30)
n=52, k=2 ? zz (distance: 52)
n=10, k=5 ? aaaaf (distance: 10)

Conclusion

The algorithm efficiently finds the lexicographically smallest string by starting with all 'a's and distributing the remaining distance from right to left. This greedy approach ensures the leftmost characters remain as small as possible while meeting the distance requirement.

---
Updated on: 2026-03-26T17:35:53+05:30

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements