Smallest String With A Given Numeric Value - Problem

Imagine you're creating a password system where each letter has a specific weight - 'a' weighs 1, 'b' weighs 2, 'c' weighs 3, and so on up to 'z' which weighs 26.

Your challenge is to create the lexicographically smallest (alphabetically first) string that meets two exact requirements:

  • It must be exactly n characters long
  • The total weight of all characters must equal exactly k

Example: If n=3 and k=27, you need a 3-character string with total weight 27. The answer is "aaz" because:

  • a(1) + a(1) + z(26) = 28... wait, that's too much!
  • a(1) + a(1) + y(25) = 27 ✓

But wait! We want the smallest lexicographically, so we should put the heaviest letters at the end to keep the beginning as small as possible.

Input & Output

example_1.py — Basic Case
$ Input: n = 3, k = 27
Output: "aay"
💡 Note: We need 3 characters with sum 27. Start with 'aaa' (sum=3), then we need 24 more. Replace the last 'a' with 'y' (adds 24), giving us 'aay' with sum 1+1+25=27.
example_2.py — Minimum Case
$ Input: n = 5, k = 73
Output: "aaszz"
💡 Note: Start with 'aaaaa' (sum=5), need 68 more. Work backwards: replace last with 'z' (+25, remaining=43), second-last with 'z' (+25, remaining=18), third-last with 's' (+18, remaining=0).
example_3.py — All Same Characters
$ Input: n = 1, k = 26
Output: "z"
💡 Note: Single character with maximum value 26 is 'z'.

Constraints

  • 1 ≤ n ≤ 105
  • n ≤ k ≤ 26 × n
  • k is always achievable (guaranteed valid input)

Visualization

Tap to expand
Making Change: The Lexicographic Waycoin 'a'coin 'b'...26¢coin 'z'Making Change for 27¢ using exactly 3 coinsStep 1: Start neat - all 1¢ coinsTotal: 3¢, Need: 24¢ moreStep 2: Replace from END with largest possible25¢Total: 27¢, Perfect!Result: "aay" - Lexicographically smallest!
Understanding the Visualization
1
Start with Smallest Coins
Begin with all 1-cent coins (all 'a' characters) - this gives the neatest receipt start
2
Work from the End
Replace coins from the end of the receipt with larger denominations
3
Use Largest Possible
At each position, use the largest coin that doesn't exceed remaining amount
4
Perfect Change
Continue until you have exact change with the neatest possible receipt
Key Takeaway
🎯 Key Insight: To get the lexicographically smallest string, always start with the smallest characters and place larger values as far right as possible!
Asked in
Google 45 Amazon 38 Meta 29 Microsoft 22
67.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen