Program to find lexicographically smallest string after applying operations in Python


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

Example

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

Input

"5323", 9, 2

Output

2050

Updated on: 05-Oct-2021

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements