Advertisement
imashutosh51

Lexicographically Smallest String After Applying Operations

Jan 15th, 2023
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 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. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement