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. For example, the numeric value of the string "abe"
is equal to 1 + 2 + 5 = 8
.
You are given two integers n
and k
. Return the lexicographically smallest string with length equal to n
and numeric value equal to k
.
Note that a string x
is lexicographically smaller than string y
if x
comes before y
in dictionary order, that is, either x
is a prefix of y
, or if i
is the first position such that x[i] != y[i]
, then x[i]
comes before y[i]
in alphabetic order.
Example 1:
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.
Example 2:
Input: n = 5, k = 73 Output: "aaszz"
Constraints:
1 <= n <= 105
n <= k <= 26 * n
The problem asks to find the lexicographically smallest string of length n
with a numeric value of k
. The numeric value of a string is the sum of the numeric values of its characters (a=1, b=2, ..., z=26).
The solution employs a greedy approach. The core idea is to prioritize using smaller characters ('a') as much as possible while ensuring the numeric value constraint (k
) is met.
Algorithm:
Initialization: Create a string ans
of length n
, filled with 'a' characters (the lexicographically smallest characters). The initial numeric value is n
(all 'a's).
Remaining Value: Calculate the remaining numeric value needed: d = k - n
. This is how much more numeric value we need to add to reach k
.
Greedy Assignment: Iterate through the string from right to left (index i
from n-1
to 0). In each iteration:
d
is greater than 25 (the maximum value of a single character), we can set the current character to 'z' (to minimize the lexicographical order) and reduce d
by 25.d
to the current character's value ('a' + d) and terminate the loop. This ensures that we don't exceed k
.Return: Convert the character array ans
to a string and return it.
Time and Space Complexity:
Code Explanations (Python Example):
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
ans = ['a'] * n # Initialize with 'a's
i, d = n - 1, k - n # i: index, d: remaining value
while d > 25: # While remaining value > 25, use 'z'
ans[i] = 'z'
d -= 25
i -= 1
ans[i] = chr(ord(ans[i]) + d) # Add the remaining value to the current character
return ''.join(ans) # Join the characters into a string
The other languages (Java, C++, Go) follow the same logic, with minor syntactic differences to handle strings and character manipulation. The core greedy approach remains consistent across all implementations.