Lexicographically Smallest String After Applying Operations - Problem
String Transformation Challenge: You're given a string
s of even length consisting only of digits (0-9), along with two integers a and b. Your goal is to find the lexicographically smallest string possible by applying these two operations any number of times:
- Add Operation: Add
ato all digits at odd indices (1, 3, 5, ...). Digits wrap around after 9 (e.g., 8+3=1, 9+2=1) - Rotate Operation: Rotate the string
bpositions to the right
s = "5525", a = 9, b = 2:
- Add 9 to odd indices: "5525" โ "5424" (5+9=4, 2+9=1)
- Rotate right by 2: "5424" โ "2454"
Input & Output
example_1.py โ Basic transformation
$
Input:
s = "5525", a = 9, b = 2
โบ
Output:
"2050"
๐ก Note:
Starting with "5525", we can apply operations: add 9 to odd indices โ "5424", rotate by 2 โ "2454", continue exploring until we find "2050" as the lexicographically smallest.
example_2.py โ Multiple rotations
$
Input:
s = "74", a = 5, b = 1
โบ
Output:
"24"
๐ก Note:
From "74": add 5 to odd indices โ "79", rotate by 1 โ "97", add 5 โ "92", rotate โ "29", add 5 โ "24". The smallest achievable string is "24".
example_3.py โ No improvement possible
$
Input:
s = "0011", a = 4, b = 2
โบ
Output:
"0011"
๐ก Note:
Starting with "0011", after exploring all possible operations, no string lexicographically smaller than "0011" can be achieved.
Visualization
Tap to expand
Understanding the Visualization
1
Start Position
Begin with the initial string configuration
2
Generate States
Apply both operations to create new possible states
3
Track Visited
Mark states as visited to avoid infinite cycles
4
Find Minimum
Keep track of the lexicographically smallest string encountered
Key Takeaway
๐ฏ Key Insight: Since the string length is finite and digits are bounded (0-9), there are only finitely many reachable states. BFS guarantees we find the lexicographically smallest string by exploring all possibilities systematically.
Time & Space Complexity
Time Complexity
O(n * 10^n)
In worst case, we might visit all possible digit combinations (10^n) and for each state we do O(n) work
โ Linear Growth
Space Complexity
O(10^n)
We store all visited states in a set, which could be up to 10^n different strings
โก Linearithmic Space
Constraints
- 2 โค s.length โค 100
- s.length is even
- s consists of digits from 0 to 9 only
- 1 โค a โค 9
- 1 โค b โค s.length - 1
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code