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 as 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.

To solve this, we will follow these steps −

  • dist := an array of size k, and fill with 1
  • credit := n - k
  • i := k - 1
  • while credit > 0, do
    • val := minimum of credit and 25
    • dist[i] := dist[i] + val
    • credit := credit - val
    • i := i - 1
  • join the (characters of (d - 1 + ASCII of "a")) for each d in dist) and return

Example

Let us see the following implementation to get better understanding −

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)

n = 15
k = 3
print(solve(n, k))

Input

15, 3

Output

aam

Updated on: 19-Oct-2021

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements