imashutosh51

Lexicographically Smallest String After Applying Operations

Jan 15th, 2023 (edited)
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. '''
  2. Logic:
  3. We will apply BFS.The time complexity allows us to see all the possibility but
  4. we will also use a map so that we won't repeat
  5. the same output.
  6. for every input,If it is present in map,means already visited this string.
  7. if not in map,compare it with the answer string.
  8. Now,two modification to do,add a to every odd position and send for bfs.
  9. second,rotate the string by b and send for bfs.
  10. '''
  11. def _add(s,a):
  12.     ans=""
  13.     for i in range(0,len(s)):
  14.         if i%2==0:
  15.             ans+=s[i]
  16.             continue
  17.         ans+=str((int(s[i])+a)%10)
  18.     return ans
  19.  
  20. def _rot(s,b):
  21.     return s[len(s)-b:]+ s[0:len(s)-b]
  22.  
  23. def bfs(s,a,b,dict,ans):
  24.     ans[0]=min(ans[0],s)
  25.     if s in dict.keys():
  26.         return
  27.     dict[s]=1
  28.     new_s=_add(s,a)
  29.     rot_s=_rot(s,b)
  30.     bfs(new_s,a,b,dict,ans)
  31.     bfs(rot_s,a,b,dict,ans)
  32.  
  33. class Solution:
  34.     def findLexSmallestString(self, s: str, a: int, b: int) -> str:
  35.         dict={}
  36.         ans=[s]
  37.         bfs(s,a,b,dict,ans)
  38.         return ans[0]
  39.        
Advertisement
Add Comment
Please, Sign In to add comment