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 <= 105n <= k <= 26 * nWhen you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you need to build a word of a specific length using letters where each letter has a number value, and the total value must match a target number while keeping the word as early in the alphabet as possible. The brute force strategy involves testing every single possible combination of letters that matches the required length to see which ones add up to the target value.
Here's how the algorithm would work step-by-step:
import itertools
def get_smallest_string_brute_force(string_length, target_value):
alphabet_string = "abcdefghijklmnopqrstuvwxyz"
# Generate every combination of letters for the required length to test all possibilities
all_combinations = list(itertools.product(alphabet_string, repeat=string_length))
valid_combinations = []
for current_combination in all_combinations:
current_numeric_value = sum(ord(current_character) - ord('a') + 1 for current_character in current_combination)
# Filter combinations to keep only those matching the exact target numeric value
if current_numeric_value == target_value:
valid_combinations.append("".join(current_combination))
# Sort alphabetically to guarantee we pick the one that comes first in lexicographical order
valid_combinations.sort()
return valid_combinations[0]
Instead of trying to guess combinations from the beginning, the optimal approach works backward from the end to build the smallest possible text. By saving the most powerful letters for the end, we ensure that earlier positions get the lightest possible letters.
Here's how the algorithm would work step-by-step:
class Solution:
def get_smallest_string(self, string_length: int, target_numeric_value: int) -> str:
character_code_list = [1] * string_length
# Baseline minimum score is achieved, calculate how much extra value remains to be distributed.
remaining_extra_score = target_numeric_value - string_length
current_index = string_length - 1
while remaining_extra_score > 0:
# Determine the maximum score we can add to this position without exceeding 'z' (value 26).
score_to_add = min(25, remaining_extra_score)
character_code_list[current_index] += score_to_add
# Once the extra score is added here, subtract it from the remaining total.
remaining_extra_score -= score_to_add
current_index -= 1
# Convert numeric character codes back into their respective alphabetic characters.
return "".join(chr(code + 96) for code in character_code_list)
| Case | How to Handle |
|---|---|
| Minimum possible inputs where n equals 1 and k equals 1 | The algorithm should place 'a' at the single position and terminate without out-of-bounds errors. |
| Maximum possible inputs where n is large and k is at its maximum possible value of 26 * n | The approach must fill the string with 'z' from right to left efficiently in linear time without performance degradation. |
| Inputs where k is at its minimum possible valid value of n, meaning every character must be 'a' | The greedy loop should leave all positions as 'a' since no remaining budget exists to increment characters. |
| Highly skewed distributions where k is much larger than n, requiring characters near 'z' at the end and 'a' at the start | Filling from the end of the string allows us to assign maximum possible values to later indices while keeping earlier indices as 'a'. |
| Invalid inputs where k is less than n or greater than 26 * n | The problem constraints typically guarantee valid inputs, but boundary checks should safely handle impossible sums without infinite loops. |
| Language-specific string immutability leading to performance overhead during construction | Using a mutable character array or string builder ensures string modifications happen in O(n) time and space complexity. |
| Integer boundary limits during intermediate calculations of remaining sum k | Standard 32-bit integers prevent any overflow issues since n and k values easily fit within standard primitive ranges. |
| Transition states where a single character partially absorbs the remaining sum k between 1 and 26 | The algorithm assigns the exact remainder offset by 1 plus the base value of 'a' to correctly finalize the last adjustable position. |