|
| 1 | +/** |
| 2 | + * 1663. Smallest String With A Given Numeric Value |
| 3 | + * https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * The numeric value of a lowercase character is defined as its position (1-indexed) in the |
| 7 | + * alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value |
| 8 | + * of c is 3, and so on. |
| 9 | + * |
| 10 | + * The numeric value of a string consisting of lowercase characters is defined as the sum of |
| 11 | + * its characters' numeric values. For example, the numeric value of the string "abe" is equal |
| 12 | + * to 1 + 2 + 5 = 8. |
| 13 | + * |
| 14 | + * You are given two integers n and k. Return the lexicographically smallest string with length |
| 15 | + * equal to n and numeric value equal to k. |
| 16 | + * |
| 17 | + * Note that a string x is lexicographically smaller than string y if x comes before y in |
| 18 | + * dictionary order, that is, either x is a prefix of y, or if i is the first position |
| 19 | + * such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} n |
| 24 | + * @param {number} k |
| 25 | + * @return {string} |
| 26 | + */ |
| 27 | +var getSmallestString = function(n, k) { |
| 28 | + const result = new Array(n).fill('a'); |
| 29 | + let remainingValue = k - n; |
| 30 | + |
| 31 | + for (let i = n - 1; i >= 0 && remainingValue > 0; i--) { |
| 32 | + const addValue = Math.min(25, remainingValue); |
| 33 | + result[i] = String.fromCharCode(97 + addValue); |
| 34 | + remainingValue -= addValue; |
| 35 | + } |
| 36 | + |
| 37 | + return result.join(''); |
| 38 | +}; |
0 commit comments