- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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
- Related Articles
- Program to find Lexicographically Smallest String With One Swap in Python
- Program to find kth smallest n length lexicographically smallest string in python
- Program to find lexicographically smallest non-palindromic string in Python
- Program to find nth smallest number from a given matrix in Python
- Python Regex to extract maximum numeric value from a string
- Program to find a good string from a given string in Python
- Program to find lexicographically smallest string after applying operations in Python
- Program to find maximum possible value of smallest group in Python
- Program to Find Out the Smallest Substring Containing a Specific String in Python
- Python Get the numeric prefix of given string
- Program to shuffle string with given indices in Python
- Find the lexicographically smallest string which satisfies the given condition in Python
- Program to find lexicographically smallest string to move from start to destination in Python
- Write a program in Python to print numeric index array with sorted distinct values in a given series
- Program to find smallest value of K for K-Similar Strings in Python

Advertisements