Permutations of a given string | Practice | GeeksforGeeks

Given a string S. The task is to print all permutations of a given string in lexicographically sorted order.
 
Example 1:
Input: ABC
Output:
ABC ACB BAC BCA CAB CBA
Explanation:
Given string ABC has permutations in 6 
forms as ABC, ACB, BAC, BCA, CAB and CBA .

Example 2:
Input: ABSG
Output:
ABGS ABSG AGBS AGSB ASBG ASGB BAGS 
BASG BGAS BGSA BSAG BSGA GABS GASB 
GBAS GBSA GSAB GSBA SABG SAGB SBAG 
SBGA SGAB SGBA
Explanation:
Given string ABSG has 24 permutations.

 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function find_permutaion() which takes the string S as input parameter and returns a vector of string in lexicographical order.
 
Expected Time Complexity: O(n! * n)
Expected Space Complexity: O(n)
 
Constraints:
1 <= length of string <= 5
 
 
0
ashok1si18ec0172 days ago
// { Driver Code Startsimport java.util.*;import java.lang.*;import java.io.*;class GFG{public static void main(String[] args) throws IOException{       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));       int t = Integer.parseInt(br.readLine().trim());       while(t-->0)       {           String S = br.readLine().trim();           Solution obj = new Solution();           List<String> ans = obj.find_permutation(S);           for( int i = 0; i < ans.size(); i++)           {               System.out.print(ans.get(i)+" ");           }           System.out.println();                              }}}
// } Driver Code Ends
class Solution {   public List<String> find_permutation(String S) {       // Code here       List<String> res = new ArrayList<String>();       int i = 0;       find(S, i, res);       Collections.sort(res);       return res;   }   public void find(String S, int i, List<String> res)   {       if(i >= S.length())       {           res.add(S);           return;       }       for(int j = i; j < S.length(); j++)       {           S = swap(S, i, j);           find(S, i+1, res);           S = swap(S, i, j);       }   }   public String swap(String a, int i, int j)   {       char temp;       char[] charArray = a.toCharArray();       temp = charArray[i] ;       charArray[i] = charArray[j];       charArray[j] = temp;       return String.valueOf(charArray);   }}
0
vishalsavade3 days ago
// This code is contributed by SK
####################Method 1#######################
void permute(string s, int l, vector<string> &res){
	        if(l == s.size()){
	           res.push_back(s);
	            return;
	        }
	        for(int i = l; i < s.size(); i++){
	            swap(s[i], s[l]);
	            permute(s, l+1, res);
	            swap(s[l], s[i]);
	        }
	    }
vector<string>find_permutation(string s){
	// Code here there
	vector<string> res;
	permute(S, 0, res);
	sort(res.begin(), res.end());
	return res;
}
###############METHOD 2#############################
vector<string>find_permutation(string s){
	// Code here there
	vector<string> res;
	sort(s.begin(), s.end());
	do{
		res.push_back(s);
	}while(next_permutation(s.begin(), s.end()));
	sort(res.begin(), res.end());
	return res;
}


0
ankitparashxr4 days ago
0.01 sec (java)
class Solution {     void permutation(String str,String asf,List<String> ans)   {       if(str.length()==0)       {           ans.add(asf);           return;       }                     for(int i=0;i<str.length();i++)       {           char ch = str.charAt(i);           String left = str.substring(0,i);           String right = str.substring(i+1);           String ros = left+right;           permutation(ros,asf+ch,ans);       }   }   public List<String> find_permutation(String s)    {        List<String> ans = new ArrayList<>();        permutation(s,"",ans);        Collections.sort(ans);        return ans;   }}
0
sahilmalhan004 days ago
//Simple Java Solution using frequency map and backtracking

public List<String> find_permutation(String S) {
        // Create a freq. map
        Map<Character, Integer> fmap = new HashMap<>();
        for(char ch : S.toCharArray()){
            if(fmap.containsKey(ch)){
                fmap.put(ch, fmap.get(ch) + 1);
            } else {
                fmap.put(ch, 1);
            }
        }
        
        List<String> ans = new ArrayList<>();
        generateWords(1, S.length(), fmap, "", ans);
        //lexicographically increasing order
        Collections.sort(ans);
        return ans;
    }
    
    public void generateWords(int cs, int ts, Map<Character, Integer> fmap, String asf, List<String> ans){
        //cs > ts means the entire string has been added to asf, then add asf to arrayList
        if(cs > ts){
            ans.add(asf);
            return;
        }
        
        for(char ch : fmap.keySet()){
            if(fmap.get(ch) > 0){
                fmap.put(ch, fmap.get(ch) - 1);
                generateWords(cs + 1, ts, fmap, asf + ch, ans);
                fmap.put(ch, fmap.get(ch) + 1);
            }
        }
    }
0
bhavdeepkaushal3925 days ago
void permut(string str,vector<string> &result , string ans =""){   if(str.length()==0){       result.push_back(ans);       return ;   }      for(int i=0;i<str.length();i++){       char ch = str[i];       string ros = str.substr(0,i)+str.substr(i+1);       permut(ros,result,ans+ch);   }}
vector<string>find_permutation(string S){    vector<string> result;    permut(S,result);    return result;
}
0
anmoljandiyal12
This comment was deleted.
0
anmoljandiyal12
This comment was deleted.
0
yaswa7792 weeks ago
I am not getting any errors but due to order changing answer is wrong can anyone help me:(
 
class Solution{public:    string res = "";        void permutation(vector<string>&result,string S,string res){        if(S.length()==0){         result.push_back(res);         return;     }          for(int i=0;i<S.length();i++){         char ch = S[i];         string leftpart = S.substr(0,i);         string rightpart = S.substr(i+1);         string val = leftpart+rightpart;         permutation(result,val,res+ch);     }    }     vector<string>find_permutation(string S) {     vector<string>result;     permutation(result,S,res);     return result;      }};
0
shinu832 weeks ago
void solve(string &s,vector<string> &ans,int index){    if(index>=s.size()){        ans.push_back(s);        return;    }    for(int j=index;j<s.size();j++){        swap(s[index],s[j]);        solve(s,ans,index+1);        swap(s[index],s[j]);    }} vector<string>find_permutation(string S) {   vector<string> ans;   int index=0;   solve(S,ans,index);   sort(ans.begin(),ans.end());   return ans;    }
0
sakesai302 weeks ago
class Solution {   public List<String> find_permutation(String S) {       ArrayList<String> kaka = new ArrayList<>();       stringPermutations(0,S.toCharArray(),S.length(),kaka);       Collections.sort(kaka);       return kaka;   }      static void stringPermutations(int index,char[] mama,int n,ArrayList<String> list) { if(index == n) {  list.add(new String(mama));  return; } for(int i =index;i<n;i++) {  swap(mama,i,index);  stringPermutations(index+1, mama, n,list);  swap(mama,i,index);   } }static void swap(char[] ch,int lo,int hi) { char temp = ch[lo]; ch[lo] = ch[hi]; ch[hi] = temp;}}
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.