Lexicographically Smallest String After Applying Operations - Problem
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:
- Operation 1: Add
ato all odd indices ofs(0-indexed). Digits post 9 are cycled back to 0. For example, ifs = "3456"anda = 5,sbecomes"3951". - Operation 2: Rotate
sto the right bybpositions. For example, ifs = "3456"andb = 1,sbecomes"6345".
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 a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input & Output
Example 1 — Basic Case
$
Input:
s = "5014", a = 9, b = 2
›
Output:
"0145"
💡 Note:
Apply operation 2 to rotate right by 2: "5014" → "1450". Then apply operation 2 again: "1450" → "0145". This gives the lexicographically smallest result.
Example 2 — Only Operation 1 Needed
$
Input:
s = "74", a = 5, b = 1
›
Output:
"24"
💡 Note:
Apply operation 1 to add 5 to odd indices: "74" → "72" (7+5=12→2). Continue: "72" → "70" → "78" → "76" → "74" → "72"... Then try rotations to get "24".
Example 3 — No Operations Needed
$
Input:
s = "0000", a = 1, b = 1
›
Output:
"0000"
💡 Note:
The string is already lexicographically smallest possible (all zeros), so no operations improve it.
Constraints
- 2 ≤ s.length ≤ 100
- s.length is even
- s consists of digits from 0 to 9
- 1 ≤ a ≤ 9
- 1 ≤ b ≤ s.length - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Original string "5014" with operations a=9, b=2
2
Apply Operations
Operation 1: Add 9 to odd indices, Operation 2: Rotate right by 2
3
Find Minimum
Explore all reachable states to find "0145"
Key Takeaway
🎯 Key Insight: Use BFS to systematically explore all reachable string states while avoiding cycles with a visited set
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code