Approach
Breadth-first search
For Lexicographically Smallest String After Applying Operations, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 74 lines of Python from the credited upstream file lexicographically-smallest-string-after-applying-operations.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution(object):5 def findLexSmallestString(self, s, a, b):6 """7 :type s: str8 :type a: int9 :type b: int10 :rtype: str11 """12 def less(s, i, j):13 for k in xrange(len(s)):14 if s[(k+i)%len(s)] != s[(k+j)%len(s)]:15 return s[(k+i)%len(s)] < s[(k+j)%len(s)]16 return False17 18 s = list(s)19 result = s[:]20 even = [False]*1021 while not even[int(s[0])]: 22 even[int(s[0])] = True23 odd = [False]*1024 while not odd[int(s[1])]: 25 odd[int(s[1])] = True26 best_rotate = 027 lookup = [False]*len(s)28 i = b29 while not lookup[i]: 30 lookup[i] = True31 if less(s, i, best_rotate): 32 best_rotate = i33 i = (i+b)%len(s)34 result = min(result, s[best_rotate:] + s[:best_rotate])35 for k in xrange(1, len(s), 2): 36 s[k] = str((int(s[k])+a) % 10)37 if b%2: 38 for k in xrange(0, len(s), 2): 39 s[k] = str((int(s[k])+a) % 10)40 return "".join(result)41 42 434445import collections46 47 48class Solution2(object):49 def findLexSmallestString(self, s, a, b):50 """51 :type s: str52 :type a: int53 :type b: int54 :rtype: str55 """56 q, lookup, result = collections.deque([s]), {s}, s57 while q:58 curr = q.popleft()59 if curr < result:60 result = curr61 add_a = list(curr) 62 for i, c in enumerate(add_a):63 if i%2:64 add_a[i] = str((int(c)+a) % 10)65 add_a = "".join(add_a) 66 if add_a not in lookup:67 lookup.add(add_a)68 q.append(add_a)69 rotate_b = curr[b:] + curr[:b]70 if rotate_b not in lookup:71 lookup.add(rotate_b)72 q.append(rotate_b)73 return result74