Skip to content

Commit 5db1ad2

Browse files
authored
Create smallest-string-with-a-given-numeric-value.cpp
1 parent f9a706d commit 5db1ad2

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string getSmallestString(int n, int k) {
7+
static const int MAX_DIFF = 'z' - 'a';
8+
9+
k -= n;
10+
string result(n, 'a');
11+
for (int i = n - 1; i >= 0 && k > 0; --i, k -= min(k, MAX_DIFF)) {
12+
result[i] = 'a' + min(k, MAX_DIFF);
13+
}
14+
return result;
15+
}
16+
};

0 commit comments

Comments
 (0)