LeetCode 1663: Smallest String With A Given Numeric Value Solution

Master LeetCode problem 1663 (Smallest String With A Given Numeric Value), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1663. Smallest String With A Given Numeric Value

Problem Explanation

Explanation

To solve this problem, we need to find the lexicographically smallest string of length n with a numeric value of k. We can achieve this by constructing the string from left to right, starting with the lexicographically smallest character 'a' and incrementing the characters until we reach the desired numeric value k.

Algorithmic Idea

  1. Initialize an empty string result.
  2. Start iterating from the first position of the string:
    • Calculate the maximum possible value that can be contributed by the remaining characters to form the target sum k.
    • If the remaining characters can achieve the target sum, append the lexicographically smallest character that can contribute to the sum.
    • Update the target sum k and move to the next position.
  3. Return the final constructed string result.

Time Complexity

The time complexity of this solution is O(n) where n is the length of the string.

Space Complexity

The space complexity of this solution is O(n) to store the final result string.

Solution Code

class Solution {
    public String getSmallestString(int n, int k) {
        StringBuilder result = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            int maxCharValue = 26 * (n - i);
            for (int j = 1; j <= 26; j++) {
                if (k - j <= maxCharValue) {
                    result.append((char)('a' + j - 1));
                    k -= j;
                    break;
                }
            }
        }
        return result.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1663 (Smallest String With A Given Numeric Value)?

This page provides optimized solutions for LeetCode problem 1663 (Smallest String With A Given Numeric Value) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1663 (Smallest String With A Given Numeric Value)?

The time complexity for LeetCode 1663 (Smallest String With A Given Numeric Value) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1663 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1663 in Java, C++, or Python.

Back to LeetCode Solutions