-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_1663_LexicographicallySmallestStringofDistK.cpp
128 lines (105 loc) · 2.58 KB
/
LC_1663_LexicographicallySmallestStringofDistK.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*
https://binarysearch.com/problems/Lexicographically-Smallest-String-of-Distance-K
Lexicographically Smallest String of Distance K
https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/
1663. Smallest String With A Given Numeric Value
*/
class Solution {
public:
string getSmallestString_1(int n, int k) {
string ans(n, 'a');
int val_sum = n; // all a's
int val_rem = 1;
int j = n-1;
while(val_rem)
{
val_rem = k - val_sum;
if(val_rem >= 25)
{
ans[j] = 'z';
val_sum += 25;
if(val_sum==k)break;
}
else
{
ans[j] = 'a' + val_rem;
break;
}
j--;
}
return ans;
}
string getSmallestString(int n, int k) {
int z_cnt = floor((k-n)/25); // count of z's
bool middle = (k-n)%25 == 0; //all z or not, bec we are substracting -1 below
int a_cnt = (n-z_cnt) - 1 + int(middle);
string as(a_cnt, 'a');
string zs(z_cnt, 'z');
if((k-n)%25 > 0)
as.push_back((k-n)%25 + 'a');
return as+zs;
}
string getSmallestString_2(int n, int k)
{
int left = 0;
int right = 0;
while(k - n >= 26)
{
k -= 26;
n--;
right++;
}
while(n > 1)
{
n--;
k -= 1;
left++;
}
string leftSide(left, 'a');
string rightSide(right, 'z');
return leftSide + (char)(k + 96) + rightSide;
}
};
// Binary Search ----------------------------------------------------------------
string solve_1(int n, int k) {
string ans;
int cntz = n/26;
int new_dist = n-cntz*26;
while(new_dist < k-cntz)
{
cntz--;
new_dist=n-cntz*26;
}
int kc = k;
while(kc>cntz+1)
{
ans+='a';
kc--;
}
if(new_dist)
ans+= (char)((new_dist-ans.size())+96);
while(cntz--)
ans+='z';
return ans;
}
string solve(int n, int k) {
string ans(k,'a');
int val_k = k;
int val_n = 0;
int j=k-1;
while(true)
{
val_n = n - val_k;
if(val_n >= 25) //'a' is already there so for z = 26-1 = 25
{
ans[j--] = 'z';
val_k += 25;
}
else
{
ans[j--] = 'a'+val_n;
break;
}
}
return ans;
}