Skip to main content
Back to problems
#1663
Medium Algorithms

Smallest string with a given numeric value

String Greedy
67.4% acceptance
Feb 25, 2026
1922
64
The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet. The numeric value of a string is the sum of its characters' numeric values. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value k.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn get_smallest_string(n: i32, k: i32) -> String {
    let (n, mut k) = (n as usize, k as i32);
    let mut result = vec![0u8; n];
    // Fill from right to left greedily
    for i in (0..n).rev() {
      // remaining positions after this = i (positions 0..i-1 still to fill)
      // each remaining position must have at least value 1
      let remaining_min = i as i32; // i positions left, each = 1
      let val = (k - remaining_min).min(26).max(1);
      result[i] = b'a' + val as u8 - 1;
      k -= val;
    }
    String::from_utf8(result).unwrap()
  }
}