Smallest String With A Given Numeric Value

Updated on 11 July, 2025
Smallest String With A Given Numeric Value header image

Problem Statement

In the given problem, every lowercase English letter is assigned a numerical value based on its position in the alphabet starting with a=1 to z=26. The aggregate numeric value of any string composed of these characters is the sum of their individual values. You are tasked to construct the lexicographically smallest string that comprises n lowercase characters and sums up to a numeric value of k.

A string is considered lexicographically smaller when compared to another if it appears earlier in dictionary order — either by being a prefix of the other string or by having earlier differing characters come earlier in the alphabet.

Examples

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

Approach and Intuition

To approach this problem efficiently, consider the following steps:

  1. Start by initializing an array of length n filled with the character 'a'. This setup gives the smallest lexicographic value initially. The sum of the values of this array starts at n since each 'a' contributes 1 to the total sum.

  2. Now, assess how much more you need to add to this initial array to reach the numeric value of k. This difference is k - n.

  3. Begin from the end of the array (the least significant position in lexicographical terms) and try to increase each character's value to bring the total sum to k without exceeding it.

  4. Calculate how much you can increase each character by potentially making it 'z' (which holds the maximum value of 26). Convert a character at a position to 'z' only if the required increment allows.

  5. Specifically for each index starting from the last position, determine how much you can add to the current character (initially 'a'). If you can add up to 25 (to reach 'z'), do so and reduce the remaining required sum accordingly. If the required sum left is less than 25, just increase the current character by the remaining sum's value.

  6. Ccontinue this process moving towards the front of the array until the entire additional sum required (k - n) is exhausted.

This approach guarantees that the produced string will not only meet the numeric value condition but also be the smallest lexicographically, as modifications are made from the end, favoring smaller changes at more significant positions in the string.

Solutions

  • C++
cpp
class Solution {
public:
    string constructMinimumString(int length, int value) {
        string output(length, 0);
        for (int idx = length - 1; idx >= 0; idx--) {
            int increment = min(value - idx, 26);
            output[idx] = (char)(increment + 'a' - 1);
            value -= increment;
        }
        return output;
    }
};

The provided C++ solution focuses on constructing the lexicographically smallest string based on a specified numeric value and length. The function constructMinimumString takes two parameters: length, which determines the string's length, and value, which is the total numeric value the resultant string must add up to based on character values (a=1, z=26).

Here's how the solution achieves the desired result:

  1. Initialize a string output of the desired length and temporarily fill it with 0.
  2. Start from the end of the string and work backward with a for-loop. This backward iteration aids in ensuring the smallest letters possible are placed at the front of the string by leaving allocation of larger values towards the end.
  3. Calculate increment as the minimum of value - idx (the remaining needed value to reach the 'value' when each previous character has consumed some) and 26 (the maximum assignable character value for 'z').
  4. Set the output[idx] to the character determined by increment + 'a' - 1. Here, 'a-1' is used to correct the 1-based indexing of character value.
  5. Decrement value by increment to reflect that portion of total value now represented by the character at output[idx].

The function ultimately returns the constructed string that meets both the length and numeric value constraints while being lexicographically the smallest possible string, ensuring an optimal and efficient solution considering the constraints.

  • Java
java
class Solution {
    public String smallestString(int length, int sum) {
        char[] chars = new char[length];
        for (int index = length - 1; index >= 0; index--) {
            int value = Math.min(sum - index, 26);
            chars[index] = (char) (value + 'a' - 1);
            sum -= value;
        }
        return new String(chars);
    }
}

In the provided Java solution for generating the lexicographically smallest string of a given length and numeric value, the code initializes an array of characters. It iterates from the end of the array to the beginning, determining the appropriate character for each position to ensure that the resultant string has the smallest lexicographical order.

Each character's numeric value is calculated by taking the minimum of the remaining sum subtracted by the index and 26 (since 'z' represents the numeric value 26). This calculation ensures that while constructing the string from the end, every character contributes optimally to the total sum without exceeding it. The ASCII value is adjusted by subtracting 1 from the resultant value and then adding it to the ASCII value of 'a', which ensures the conversion reflects correct character positions in the alphabet. After each iteration, the sum is decremented by the numeric value used for the current character.

This approach effectively builds the string from right to left, placing the highest possible values at the end, thus satisfying both the length and sum constraints while producing the smallest possible string in lexicographic order. The use of Java's character arithmetic helps in directly translating numeric values to their corresponding alphabetic characters efficiently.

Comments

No comments yet.