MediumNo. 1663

Smallest String With A Given Numeric Value — LeetCode 1663 Python Solution

Pattern
Greedy
Topics
Greedy, String
Reading time
2 min

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

PythonSolution
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

Time
O(n)where n is the length of the string
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0316Remove Duplicate LettersMedium
0402Remove K DigitsMedium
0420Strong Password CheckerHard
0649Dota2 SenateMedium
0680Valid Palindrome IIEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.