Skip to content

1663. Smallest String With A Given Numeric Value 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  string getSmallestString(int n, int k) {
    string ans;

    for (int i = 0; i < n; ++i) {
      const int remainingLetters = n - 1 - i;
      const int rank = max(1, k - remainingLetters * 26);
      ans += 'a' + rank - 1;
      k -= rank;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public String getSmallestString(int n, int k) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < n; ++i) {
      final int remainingLetters = n - 1 - i;
      final int rank = Math.max(1, k - remainingLetters * 26);
      sb.append((char) ('a' + rank - 1));
      k -= rank;
    }

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def getSmallestString(self, n: int, k: int) -> str:
    ans = []

    for i in range(n):
      remainingLetters = n - 1 - i
      rank = max(1, k - remainingLetters * 26)
      ans.append(chr(ord('a') + rank - 1))
      k -= rank

    return ''.join(ans)