- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- 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
- JavaScript Program to Find Lexicographically smallest rotated sequence
- Find the lexicographically smallest string which satisfies the given condition in Python
- Lexicographically Smallest Equivalent String in C++
- Program to find smallest value of K for K-Similar Strings in Python
- Python program to remove K length words in String
- Find K-th Smallest Pair Distance in C++
- 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
- JavaScript Program to Find Lexicographically minimum string rotation

Advertisements