Advertisement
imashutosh51

Lexicographically Smallest String After Applying Operations

Jan 15th, 2023 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 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. unordered_map<string,int> mp;
  12. string ans;
  13. void bfs(string s,int a,int b){
  14.     if(mp[s]) return;
  15.     mp[s]=1;
  16.     if(s.compare(ans)<0) ans=s;
  17.     string backup=s;
  18.     for(int i=1;i<s.size();i+=2){
  19.         int temp=s[i]-'0';
  20.         temp+=a;
  21.         temp%=10;
  22.         s[i]=temp+'0';
  23.     }
  24.     bfs(s,a,b);
  25.     s=backup;
  26.     s=s.substr(s.size()-b,b)+s.substr(0,s.size()-b);
  27.     bfs(s,a,b);
  28. }
  29. class Solution {
  30. public:
  31.     string findLexSmallestString(string s, int a, int b) {
  32.        ans=s;
  33.        bfs(s,a,b);
  34.        return ans;
  35.     }
  36. };
  37.  
  38. #Python
  39. def _add(s,a):
  40.     ans=""
  41.     for i in range(len(s)):
  42.         if i%2==0:
  43.             ans+=s[i]
  44.         else:
  45.             ans+=str((int(s[i])+a)%10)
  46.     return ans
  47.  
  48. def _move(s,b):
  49.     return s[len(s)-b:]+s[:len(s)-b]
  50.  
  51. ans='0'
  52. def fun(s,a,b,dict):
  53.     global ans
  54.     if s in dict.keys():
  55.         return
  56.     dict[s]=1
  57.     if s<ans:
  58.         ans=s
  59.     fun(_add(s,a),a,b,dict)
  60.     fun(_move(s,b),a,b,dict)
  61.  
  62. class Solution:
  63.     def findLexSmallestString(self, s: str, a: int, b: int) -> str:
  64.         global ans
  65.         ans=s
  66.         dict={}
  67.         fun(s,a,b,dict)
  68.         return ans
  69.        
  70.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement