Difficulty: Medium
Topics: String Manipulation, BFS, Math, Simulation
You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.
You can apply either of the following two operations any number of times and in any order on s:
a to all odd indices of s (0-indexed).Example:
Ifs = "3456"anda = 5,
thensbecomes "3951".
s to the right by b positions.
Example:
Ifs = "3456"andb = 1,
thensbecomes "6345".
Your task is to return the lexicographically smallest string you can obtain by applying the above operations any number of times on s.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where they differ,
the character in a is smaller than the character in b.
Example:
"0158" is lexicographically smaller than "0190"
because they differ at the third character ('5' < '9').
Input: s = "5525", a = 9, b = 2
Output: "2050"
Explanation: We can apply the following operations:
| Step | Operation | Result |
|---|---|---|
| 1 | Start | 5525 |
| 2 | Rotate | 2555 |
| 3 | Add | 2454 |
| 4 | Add | 2353 |
| 5 | Rotate | 5323 |
| 6 | Add | 5222 |
| 7 | Add | 5121 |
| 8 | Rotate | 2151 |
| 9 | Add | 2050 ✅ |
There is no way to obtain a string smaller than "2050".
Input: s = "74", a = 5, b = 1
Output: "24"
Explanation:
Start → "74"
Rotate → "47"
Add → "42"
Rotate → "24"
There is no smaller string than "24".
Input: s = "0011", a = 4, b = 2
Output: "0011"
Explanation:
No sequence of operations can give a smaller string than "0011".
Loading component...
Loading component...