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 a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s becomes "3951".
  • Operation 2: Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "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
Lexicographically Smallest String After OperationsInput: "5014"a = 9, b = 2Operation 1Add 9 to odd indices"5014" → "5904"Operation 2Rotate right by 2"5014" → "1450"Lexicographically Smallest:"0145"Apply operations repeatedly until finding the lexicographically smallest reachable string
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
Asked in
Google 15 Facebook 12 Amazon 8
24.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen