Skip to content

Commit 0ef6f29

Browse files
authored
Create 1625. Lexicographically Smallest String After Applying Operations
1 parent 8042c7e commit 0ef6f29

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public:
3+
string findLexSmallestString(const string& s, int a, int b) {
4+
int n = s.size();
5+
6+
// Precompute minimal addition steps for each digit
7+
vector<int> bestAdd(10);
8+
for (int d = 1; d < 10; d++) {
9+
int minVal = d, minStep = 0;
10+
for (int step = 1; step < 10; step++) {
11+
int newVal = (d + a * step) % 10;
12+
if (newVal < minVal) {
13+
minVal = newVal;
14+
minStep = step;
15+
}
16+
}
17+
bestAdd[d] = minStep;
18+
}
19+
20+
// Determine rotation cycle positions reachable by repeatedly rotating
21+
// by b
22+
vector<char> visited(n);
23+
int idx = 0;
24+
while (!visited[idx]) {
25+
visited[idx] = 1;
26+
idx = (idx + b) % n;
27+
}
28+
29+
string answer = s;
30+
31+
// For each unique rotation
32+
for (int start = 0; start < n; start++) {
33+
if (!visited[start])
34+
continue;
35+
36+
string rotated = s;
37+
rotate(rotated.begin(), rotated.begin() + start, rotated.end());
38+
39+
// Compute how many times to apply 'add a' on odd/even positions
40+
vector<int> addCount = {(b % 2) ? bestAdd[rotated[0] - '0'] : 0,
41+
bestAdd[rotated[1] - '0']};
42+
43+
// Apply the addition operation accordingly
44+
for (int j = 0; j < n; j++) {
45+
int digit = rotated[j] - '0';
46+
digit = (digit + addCount[j % 2] * a) % 10;
47+
rotated[j] = static_cast<char>('0' + digit);
48+
}
49+
50+
answer = min(answer, rotated);
51+
}
52+
53+
return answer;
54+
}
55+
};

0 commit comments

Comments
 (0)