-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathSmallestStringWithAGivenNumericValue.java
72 lines (58 loc) · 1.26 KB
/
SmallestStringWithAGivenNumericValue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// @saorav21994
// TC : O(n)
// SC : O(n)
class Solution {
public String getSmallestString(int n, int k) {
char [] res = new char[n];
Arrays.fill(res, 'a');
k -= n;
while (k > 0) {
res[--n] += Math.min(25, k);
k -= Math.min(25, k);
}
return String.valueOf(res);
}
}
class Solution {
public String getSmallestString(int n, int k) {
char[] ans = new char[n];
int i = 0 ;
while(i<n){
ans[i] = 'a';
i++;
}
k = k - n;
int j = n-1;
while(k>0){
if(k<25){
ans[j] = (char)('a' + k);
k = 0;
} else {
ans[j] = 'z';
k = k - 25;
}
j--;
}
return new String(ans);
}
}
// Author: @romitdutta10
// TC: O(N)
// SC: O(N)
// Problem : https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/
class Solution {
public String getSmallestString(int n, int k) {
k = k - n;
int zcount = k / 25;
int value = k % 25;
int count = n-1;
char c[] = new char[n];
Arrays.fill(c, 'a');
while(zcount-- > 0) {
c[count--] = 'z';
}
if(value > 0)
c[count--] = (char)('a' + value);
return new String(c);
}
}