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


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

So, if the input is like n = 4 k = 16, then the output will be "aaam" because here the numeric value is 1+1+1+13 = 16, and this is smallest string with such a value and length is 4.

To solve this, we will follow these steps −

  • string := blank string
  • while n > 0 is non-zero, do
    • letter := minimum of 26 and k-n+1
    • string := string concatenate corresponding letter from alphabet position value letter
    • k := k - letter
    • n := n - 1
  • reverse the string and return

Example

Let us see the following implementation to get better understanding −

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
print(solve(n, k))

Input

4, 16

Output

aaam

Updated on: 05-Oct-2021

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements