#1663
Smallest String With A Given Numeric Value
MediumStringGreedyGreedyTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of generating all strings, we can construct the desired string directly. By starting from the end of the string and placing the highest possible character at each position, we ensure that we get the smallest lexicographical order.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a character array of size n filled with 'a'.
- 2Step 2: Calculate the remaining value needed by subtracting n from k.
- 3Step 3: Iterate from the end of the array to the beginning, placing the maximum possible character at each position until the remaining value is exhausted.
solution.py9 lines
1def smallestString(n, k):
2 result = ['a'] * n
3 k -= n
4 for i in range(n - 1, -1, -1):
5 if k > 0:
6 add = min(25, k)
7 result[i] = chr(ord('a') + add)
8 k -= add
9 return ''.join(result)ℹ
Complexity note: The time complexity is O(n) because we only iterate through the string once to fill it, and the space complexity is O(n) due to the character array used to store the result.
- 1Building the string from the end allows for maximum flexibility in choosing characters.
- 2The greedy approach ensures that we always use the smallest possible characters first.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.