- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- Program to find kth smallest n length lexicographically smallest string in python
- Program to find lexicographically smallest subsequence of size k in Python
- Program to find lexicographically smallest non-palindromic string in Python
- Program to find Lexicographically Smallest String With One Swap in Python
- Program to find lexicographically smallest string after applying operations in Python
- Program to find lexicographically smallest string to move from start to destination in Python
- Find K-th Smallest Pair Distance in C++
- Lexicographically Smallest Equivalent String in C++
- Program to find smallest value of K for K-Similar Strings in Python
- Find the lexicographically smallest string which satisfies the given condition in Python
- Program to find maximum length of k ribbons of same length in Python
- Program to find length of smallest sublist that can be deleted to make sum divisible by k in Python
- Find n-th lexicographically permutation of a strings in Python
- Python – Remove Elements in K distance with N
- Program to find smallest pair sum where distance is not consecutive in Python

Advertisements