Program to find smallest string with a given numeric value in Python

Given two values n and k, we need to find the lexicographically smallest string whose length is n and numeric value equals k. The numeric value of a lowercase character is its position in the alphabet (starting from 1), so 'a' = 1, 'b' = 2, and so on. The numeric value of a string is the sum of its characters' numeric values.

For example, if n = 4 and k = 16, the output will be "aaam" because the numeric value is 1+1+1+13 = 16, and this is the smallest string with length 4 and value 16.

Algorithm

To solve this problem, we follow these steps:

  • Create an empty string to build our result
  • While n > 0:
    • Calculate letter = min(26, k-n+1)
    • Add the corresponding alphabet character to our string
    • Subtract letter from k and decrement n
  • Reverse the string and return it

How the Algorithm Works

The key insight is to place the largest possible characters at the end of the string. We work backwards by calculating the maximum character we can place while ensuring we can still form a valid string with the remaining positions.

Implementation

def solve(n, k):
    string = ""
    while n > 0:
        letter = min(26, k - n + 1)
        string += chr(letter + ord('a') - 1)
        k -= letter
        n -= 1
    return string[::-1]

n = 4
k = 16
result = solve(n, k)
print(f"Smallest string with length {n} and value {k}: {result}")

# Verify the result
total_value = sum(ord(char) - ord('a') + 1 for char in result)
print(f"Verification - Length: {len(result)}, Value: {total_value}")
Smallest string with length 4 and value 16: aaam
Verification - Length: 4, Value: 16

Step-by-Step Trace

Let's trace through the algorithm with n = 4, k = 16:

def solve_with_trace(n, k):
    string = ""
    step = 1
    print(f"Initial: n={n}, k={k}")
    
    while n > 0:
        letter = min(26, k - n + 1)
        char = chr(letter + ord('a') - 1)
        string += char
        print(f"Step {step}: letter={letter}, char='{char}', string='{string}'")
        k -= letter
        n -= 1
        print(f"        Updated: k={k}, n={n}")
        step += 1
    
    result = string[::-1]
    print(f"Final result after reversing: '{result}'")
    return result

solve_with_trace(4, 16)
Initial: n=4, k=16
Step 1: letter=13, char='m', string='m'
        Updated: k=3, n=3
Step 2: letter=1, char='a', string='ma'
        Updated: k=2, n=2
Step 3: letter=1, char='a', string='maa'
        Updated: k=1, n=1
Step 4: letter=1, char='a', string='maaa'
        Updated: k=0, n=0
Final result after reversing: 'aaam'

Example with Different Values

def solve(n, k):
    string = ""
    while n > 0:
        letter = min(26, k - n + 1)
        string += chr(letter + ord('a') - 1)
        k -= letter
        n -= 1
    return string[::-1]

# Test with different values
test_cases = [(3, 27), (5, 73), (2, 28)]

for n, k in test_cases:
    result = solve(n, k)
    value = sum(ord(char) - ord('a') + 1 for char in result)
    print(f"n={n}, k={k} ? '{result}' (value: {value})")
n=3, k=27 ? azz
n=5, k=73 ? azzz
n=2, k=28 ? bz

Conclusion

This algorithm efficiently constructs the lexicographically smallest string by greedily placing the largest possible characters at the end and reversing the result. The time complexity is O(n) and space complexity is O(n) for the result string.

Updated on: 2026-03-26T13:53:44+05:30

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements