Smallest String With A Given Numeric Value — LeetCode 1663 Python Solution
- Problem
- #1663
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values.
Example
- Input
- n = 3, k = 27
- Output
- "aay"
- Explanation
- The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.
Python solution
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
ans = ['a'] * n
i, d = n - 1, k - n
while d > 25:
ans[i] = 'z'
d -= 25
i -= 1
ans[i] = chr(ord(ans[i]) + d)
return ''.join(ans)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1663. Smallest String With A Given Numeric Value is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1663. Smallest String With A Given Numeric Value?
- LeetCode 1663. Smallest String With A Given Numeric Value is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1663. Smallest String With A Given Numeric Value?
- The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 1663. Smallest String With A Given Numeric Value?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1663. Smallest String With A Given Numeric Value cover?
- LeetCode 1663. Smallest String With A Given Numeric Value is tagged Greedy and String on LeetCode.