Choose and Swap | Practice | GeeksforGeeks

You are given a string s of lower case english alphabets. You can choose any two characters in the string and replace all the occurences of the first character with the second character and replace all the occurences of the second character with the first character. Your aim is to find the lexicographically smallest string that can be obtained by doing this operation at most once.
Example 1:
Input:
A = "ccad"
Output: "aacd"
Explanation:
In ccad, we choose a and c and after 
doing the replacement operation once we get, 
aacd and this is the lexicographically
smallest string possible. 
 
Example 2:
Input:
A = "abba"
Output: "abba"
Explanation:
In abba, we can get baab after doing the 
replacement operation once for a and b 
but that is not lexicographically smaller 
than abba. So, the answer is abba. 

Your Task:  
You don't need to read input or print anything. Your task is to complete the function chooseandswap() which takes the string A as input parameters and returns the lexicographically smallest string that is possible after doing the operation at most once.

Expected Time Complexity: O(|A|) length of the string A
Expected Auxiliary Space: O(1)
 
Constraints:
1<= |A| <=105
 
0
anutiger2 days ago
        int arr[26];
        int md = INT_MAX - 1;
        for(int i  = 0 ; i <26 ; i++){
            arr[i] = md;
        }
        for(int i =  0 ; i < a.length() ; i ++){
            if(arr[a[i] - 'a'] == md){
                arr[a[i] - 'a'] = i;
            }
            
        }
        int swap1 = -1;
        int swap2 = -1;
        for(int  i = 0; i < 26 ; i ++){
            if(arr[i] == md) continue;
            for(int j = i + 1; j < 26 ; j ++){
                if(arr[j] < arr[i]){
                    if(swap1 == -1){
                        swap1 = arr[i]; swap2 = arr[j];
                    }
                    else{
                          if(swap2 > arr[j]){
                              swap2  = arr[j];
                          }  
                    }
                }
            }
            if(swap1 != -1){
                break;
            }
        }
        if(swap1 == INT_MAX){
            return a;
        }
        char c1 = a[swap1];
        char c2 = a[swap2];
        for(int i = 0 ; i < a.length() ; i ++){
            if(a[i] == c1){
                a[i] = c2;
            }
            else if(a[i] == c2){
                a[i] = c1;
            }
        }
        return a;
    }
0
bhaskarmaheshwari82 weeks ago
   //refer this video https://www.youtube.com/watch?v=AiDrMFMxxnQ       vector<int> vec(26,-1);       int n=str.size();       for(int i=0;i<n;i++)       {           if(vec[str[i]-'a']==-1)           vec[str[i]-'a']=i;       }              int i;       char ch,ch1;       for(  i=0;i<n;i++)       {           bool flag=0;                      for(int j=0;j<str[i]-'a';j++)           {               if(vec[j]>vec[str[i]-'a'])               {                   ch=j+'a';                   ch1=str[i];                   flag=1;                   break;               }                          }           if(flag)           break;       }       if(i<n)       {           for(int j=0;j<n;j++)           {               if(str[j]==ch)               str[j]=ch1;               else if(str[j]==ch1)               str[j]=ch;           }       }              return str;          }   
+1
rp212 weeks ago
Concise code, you'd like to see!
 
       int FI[26];       memset(FI, -1, 26 << 2);              int n = s.size();       for(int i = 0; i < n; i++){           if(FI[s[i] - 'a'] == -1){               FI[s[i] - 'a'] = i;           }       }              for(int i = 0; i < n; i++){           for(int j = 0; j < (s[i] - 'a'); j++){               if(FI[j] > i){                   int x = s[i];                   int y = 'a' + j;                   for(int i = 0; i < n; i++){                       if(s[i] == x){                           s[i] = y;                       } else if(s[i] == y){                           s[i] = x;                       }                   }                   return s;               }           }       }       return s;   }
-1
neerajchatterjee23013 weeks ago
string chooseandswap(string s){              int n = s.size();              if(n == 1) return s;              int hash[26];       memset(hash, -1, sizeof(hash));              for(int i=0; i<n; i++){           if(hash[s[i] - 'a'] == -1){               hash[s[i] - 'a'] = i;           }       }       int idx1 = -1, idx2 = -1;       bool flg = 0;              for(int i=0; i<n; i++){           int ch = s[i];           for(int j = 0; j<26; j++){               if(hash[j] > i){                   if(j < ch-'a'){                       idx1 = i;                       idx2 = hash[j];                       flg = 1;                       break;                   }               }           }           if(flg) break;       }              if(idx1 == -1 and idx2 == -1) return s;              char ch1 = s[idx1];       char ch2 = s[idx2];                     for(int i=0; i<n; i++){           if(s[i] == ch1) s[i] = ch2;           else if(s[i] == ch2) s[i] = ch1;       }              return s;      }
0
18pa1a04771 month ago
python o(n) time o(1) space
class Solution:
    def chooseandswap (self, A):
        arr=[]
        for l in range(26):
            arr.append(0)
        for  k in A:
            arr[ord(k)-ord("a")]=arr[ord(k)-ord("a")]+1
        # ct=[arr[0]]
        # for l in range(1,26):
        #     ct.append(ct[-1]+arr[l])
        ans={}
        for ch in A:
            f=False
            for l in range(ord(ch)-ord("a")):
                if arr[l]>0:
                    ans[chr(ord("a")+l)]=ch
                    ans[ch]=chr(ord("a")+l)
                    f=True
                    break
            arr[ord(ch)-ord("a")]=0
            if f:
                break
        st=""
        for l in A:
            if l in ans:
                st=st+ans[l]
            else:
                st=st+l
        return st
 
0
mdaman700751 month ago
 
T.C:- O(n)
S.C:- O(1) 
 
   string chooseandswap(string a){              vector<int> m(123,-1);       int n=a.length();              for(int i=0;i<n;i++){           if(m[a[i]]==-1)      m[a[i]]=i;       }              char ch='\0',ch2='\0';              for(int i=0;i<n;i++){           for(int j=97;j<a[i];j++){                             if(m[char(j)]>m[a[i]]){                   ch=a[i];                   ch2=j;                   break;                }                           }                     if(ch) break;       }          if(ch){          for(int k=0;k<n;k++){          if(a[k]==ch)  a[k]=ch2;          else if(a[k]==ch2)  a[k]=ch;          }       }           return a;                  }
0
ashutosh441 month ago
Java solution:
 
class Solution{   String chooseandswap(String a){       int n = a.length();       int[] c = new int[26];       Arrays.fill(c,-1);       for(int i=0;i<n;i++){           if(c[a.charAt(i)-'a']==-1){               c[a.charAt(i)-'a'] = i;           }       }       char s = '&';       char e = '&';       for(int i=0;i<n;i++){           char ct = a.charAt(i);           int id = a.charAt(i)-'a';
           for(int j=0;j<id;j++){               if(c[j]>-1 && c[j] > c[id]){                   s = ct;                   e = (char)(j+'a');                                      break;               }           }           if(s!='&' && e!='&'){               break;           }       }       StringBuilder t = new StringBuilder(a);       for(int i=0;i<n;i++){           if(t.charAt(i)==s){               t.setCharAt(i,e);           }else if(t.charAt(i)==e){               t.setCharAt(i,s);           }       }              return String.valueOf(t);   }}
-6
itsmohitmk991 month ago
Java - O(N logN))
 
class Solution{
   String chooseandswap(String str){
        int n = str.length();
    
        TreeSet<Character> set = new TreeSet<>();
        for(int i = 0; i < str.length() ; i++){
            set.add(str.charAt(i));
        }
        
        Iterator it = set.iterator();
        HashMap<Character , Integer> map = new HashMap<>();
        
        char curr = (char)it.next();
        char c1 = '1' , c2 = '1';
        
        
        for(int i = 0 ; i< n ; i++){
            if(str.charAt(i) == curr){
                map.put(str.charAt(i) , 1);
                if(it.hasNext())
                    curr = (char)it.next();
            }
            else if(map.containsKey(str.charAt(i))){
                continue;
            }
            else{
                c1 = str.charAt(i);
                c2 = curr;
                break;
            }
        }
        
        if(c1 == '1')
            return str;
        
        StringBuilder sb = new StringBuilder();
        
        for(int i = 0; i< n ; i++){
            char ch = str.charAt(i);
            if(ch == c1){
                sb.append(c2);
            }
            else if(ch == c2){
                sb.append(c1);
            }
            else{
                sb.append(ch);
            }
        }
        
        return sb.toString();
    }
    
}
0
rahulmallick11151 month ago
Time Complexity     : O(N)
Space Complexity    : O(1)
string chooseandswap(string a){
        int found[26] = {0};
        char max_so_far = CHAR_MIN ;
        char smallest   = CHAR_MAX ;
        for(int i = 0  ; i < a.size() ; ++i){
            if(found[a[i] - 'a'] == 0 && a[i] < max_so_far){
                for(int j = i ; j < a.size() ; ++j){
                    if(found[a[j] - 'a'] == 0){
                        smallest = min(smallest , a[j]) ;
                    }
                    found[a[j] - 'a'] = 1 ;
                }
                for(int j = i - 1 ; j >= 0 ; --j){
                    if(a[j] > smallest){
                        max_so_far = a[j] ;
                    }
                }
                break;
            }
            max_so_far = max(max_so_far , a[i]);
            found[a[i] - 'a'] = 1 ;
        }
        if(max_so_far != CHAR_MIN && smallest != CHAR_MAX){
            for(int i = 0 ; i < a.size() ; ++i){
                if(a[i] == max_so_far){
                    a[i] = smallest ;
                }
                else if(a[i] == smallest){
                    a[i] = max_so_far ;
                }
            }
        }
        return a;
    }
0
akkiashu6805371 month ago
#can any one help me out from this-why my output is always changing? . I think i  am not aware  of some of the property of dictionary(mapping) which is continuously changing here .
#actually this code is done in O(k*n) or we can say O(n) in space time complexity. Pls help  me out from this with this code.
def isequal(self,x,y):              for i in range(len(x)):           if x[i]!=y[i]:               return False                  return True      def chooseandswap (self, A):       # code here       d={}       for i in A:           if i not in d:               d[i]=1           else:               d[i]+=1       k=[ch for ch in d.keys()]       k1=[ch for ch in d.keys()]       k1.sort()       if self.isequal(k1,k):           return A       ans=''           v=[i for i in d.values()]       for i in range(len(v)):           temp=k1[i]*v[i]           ans+=temp                             return ans 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.