Suppose we have a string s with only numeric digits and also have two values a and b. We can apply any one of the following two operations any number of times and in any order on s −
Add 'a' to all odd positioned items of s(0-indexed). If digit is 9, then by adding something with it will be cycled back to 0.
Rotate 's' to the right by b positions.
So we have to find the lexicographically smallest string we can get by applying the above operations any number of times on s.
So, if the input is like s = "5323" a = 9 b = 2, then the output will be 2050 because if we follow
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import deque def add_(s,a): res = '' for idx, i in enumerate(s): if idx % 2 == 1: num = (int(i) + a) % 10 res += str(num) else: res += i return res def rotate_(s, b): idx = len(s)-b res = s[idx:] + s[0:idx] return res def solve(s, a, b): seen = set() deq = deque([s]) while deq: curr = deq.popleft() seen.add(curr) ad = add_(curr, a) if ad not in seen: deq.append(ad) seen.add(ad) ro = rotate_(curr, b) if ro not in seen: deq.append(ro) seen.add(ro) return min(seen) s = "5323" a = 9 b = 2 print(solve(s, a, b))
"5323", 9, 2