Program to find lexicographically smallest string after applying operations in Python

PythonServer Side ProgrammingProgramming

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

  • Rotate: "5323"
  • Add: "5222"
  • Add: "5121"
  • Rotate: "2151"
  • Add: "2050"

To solve this, we will follow these steps −

  • seen := a new set
  • deq := a new queue with one element 's'
  • while deq is not empty, do
    • curr := first deleted element of deq
    • insert curr into seen set
    • ad := perform given add operation on curr
    • if ad is not in seen, then
      • insert ad at the end of deq
      • insert ad into seen set
    • ro := perform rotate operation on curr
    • if ro is not in seen, then
      • insert ro at the end of deq
      • insert ro into seen set
  • return minimum of seen


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)
         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()

      ad = add_(curr, a)
      if ad not in seen:

      ro = rotate_(curr, b)
      if ro not in seen:

   return min(seen)

s = "5323"
a = 9
b = 2
print(solve(s, a, b))


"5323", 9, 2


Published on 05-Oct-2021 11:25:54