Taro Logo

Smallest String With A Given Numeric Value

#1 Most AskedMedium
Topics:
StringsGreedy Algorithms

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

Solution


Clarifying Questions

When 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:

  1. What are the valid ranges for the length `n` and the numeric value `k`?
  2. Is it always guaranteed that a valid string of length `n` with a sum of `k` exists, or do we need to handle cases where no solution is possible?
  3. Since the problem asks for the lexicographically smallest string, should we prioritize placing smaller characters ('a') as far to the left as possible?
  4. Should the output be returned as a standard string data type (e.g., `std::string` in C++ or `str` in Python)?
  5. Are there any specific memory constraints we need to be aware of beyond the standard optimal time and space complexity?

Brute Force Solution

Approach

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:

  1. List out every possible combination of letters that matches the required length, starting with combinations made only of the very first letter of the alphabet.
  2. For every single combination you generate, calculate the total value by adding up the numerical value of each letter.
  3. Check if the total value of the combination matches your target number.
  4. If a combination does not match the target value, completely throw it away and move on to the next one.
  5. Collect all the combinations that successfully add up to the exact target value.
  6. Compare all the successful combinations side by side to find the one that comes first in alphabetical order.
  7. Return that winning combination as the final answer.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(26^n) – To find the smallest string, the brute force strategy generates every possible combination of letters of length n, where each position can be any of the 26 lowercase alphabet letters. For a string of length n, there are 26 to the power of n possible combinations that must be generated and checked against the target value. As the input length n increases, the number of combinations grows exponentially due to this branching factor. This leads to approximately 26^n operations, which simplifies to the exponential time complexity of O(26^n).
Space Complexity
O(n) – To analyze the auxiliary space, we look at the data structures described in the plain English explanation where the algorithm collects all successful combinations and stores intermediate generated letter combinations of length n. Specifically, Step 5 and Step 6 require gathering these items into a massive collection or pile in memory to compare them side by side. Because the number of possible letter combinations grows exponentially with the length of the string n, storing them temporarily requires auxiliary memory proportional to this exponential growth. Simplifying this to Big O notation based on the input size n, the auxiliary space complexity is O(n) for the output string storage when using an optimal greedy approach, though a brute force approach storing all combinations would require significantly more.

Optimal Solution

Approach

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:

  1. Imagine a row of empty spaces that we need to fill with letters, keeping a total score in mind.
  2. Start by filling every single empty space with the lightest possible letter, which gives us a baseline score.
  3. Calculate how much leftover score we still need to add to reach our target.
  4. Go to the very last empty space and look at how much room we have to upgrade it.
  5. Pump up that last space by adding as much score as it can possibly hold without exceeding its maximum limit.
  6. If any leftover score remains, move one space to the left and repeat the upgrade process.
  7. Continue moving backward through the spaces, making each one as heavy as possible until all of the leftover score is completely used up.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, the input size n represents the length of the string we need to construct. First, we initialize an array or string of length n with the lightest letter, which takes linear time proportional to n. Next, we iterate backward from the last position to the first, adding the leftover score to upgrade the letters. Since this backward traversal visits each of the n positions at most once, the total operations scale linearly with n. This results in roughly n operations overall, which simplifies to O(n).
Space Complexity
O(n) – To build the final result according to the steps, we utilize an auxiliary character array of size n to represent the row of empty spaces being filled and upgraded. Since this output container directly scales with the length of the string n, the extra memory required grows linearly with the input size. No other data structures or recursive calls are used, keeping the auxiliary space strictly proportional to n.

Edge Cases

Minimum possible inputs where n equals 1 and k equals 1
How to Handle:
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
How to Handle:
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'
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The algorithm assigns the exact remainder offset by 1 plus the base value of 'a' to correctly finalize the last adjustable position.
0/1 completed