Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Day 13 : All Possible Permutations - String

Easy
0/40
Average time to solve is 30m
profile
Contributed by
124 upvotes
Asked in companies
CiscoWalmartHSBC

Problem statement

You are given an input string 'S'. Your task is to find and return all possible permutations of the input string.

Note:
1. The input string may contain the same characters, so there will also be the same permutations.

2. The order of permutation does not matter.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first and only line of input contains a string 'S' of alphabets in lower case characters.
Output Format:
Print all the permutations of the given string 'S' in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.    
Constraint:
1 <= |S| <= 8

Where |S| denotes the length of string 'S'.

Time limit: 1 sec
Sample Input 1:
cba
Sample Output 1:
abc
acb
bac
bca
cab
cba
Explanation for Sample Output 1:
All the possible permutations for string "cba" will be "abc", "acb", "bac", "bca", "cab" and "cba".
Sample Input 2:
xyx
Sample Output 2:
xyx
xxy
yxx
yxx
xyx
xxy
Explanation for Sample Output 2:
All the possible permutations for string "xyx" will be "xyx", "xxy", "yxx", "yxx", "xyx" and "xxy". Here, all three permutations "xyx", "yxx", "xxy" are repeating twice but we need to print all the possible permutations and hence we are printing them twice..
Hint

Think about how you can break this problem between the first character of the string and the rest of it.

Approaches (1)
Backtracking

We can find all the permutations by Backtracking.

 

1: Fix a character then swap all the rest of the remaining character with a fixed character.

2: Then find all permutations for all remaining characters by the recursive call.

3: The base case for the recursion will be when there is only one character left unprocessed.

 

Below is the illustration to approach.

 

Time Complexity

O(N*N!), where N is the length of the String.

 

In the worst case, there will be N! Recursion calls and for each permutation, it requires O(N) time to print. Thus the overall time complexity will be O(N*N!).

Space Complexity

O(N), where N is the length of the string.

 

Because O(N) extra space is required for recursion stack and thus space complexity will be O(N).

Code Solution
(100% EXP penalty)
Day 13 : All Possible Permutations - String
All tags
Sort by
Search icon

Interview problems

Simple java solution 98%- Recursion

In below code we will be using simple recursion to create all possible permutations.

  • we will be creating an inp array, for convienience as we wil be removing elements from this array each time we append to the result, so that the next permtn will exclude already used elements.
  • Stringbuilder is used to append each char.

Algo;

 

    if input array is empty, i.e no more elements need to be added, store the string in result.

 

else travel through the input array, append the char to stringBuilder, remove it from input arrayList

and call append method again.

After returning, revert back the changes.

 

Kl refer below code

 

import java.util.* ;

import java.io.*; 

public class Solution {

    public static List<String> findPermutations(String s) {

        List<String> res = new ArrayList<>();

        List<Character> inp = new ArrayList<>(s.length());

        for(int i=0; i<s.length(); i++)

            inp.add(s.charAt(i));

        StringBuilder b = new StringBuilder();

        append(b, inp, res);

        return res;

    }




    public static void append(StringBuilder b, List<Character> inp, List<String> res){

        if(inp.size() == 0){

            res.add(b.toString());

            return;

        }

        for(int i=0; i<inp.size(); i++){

            char c = inp.get(i);

            b.append(c);

            inp.remove(i);

            append(b, inp, res);

            inp.add(i, c);

            b.deleteCharAt(b.length()-1);

        }

    }

}

 

Happy coding  ; ~)

 

 

8 views
0 replies
0 upvotes

Interview problems

easy cpp

#include <bits/stdc++.h> 

using namespace std;

void TP(string &s, vector<string> &ans,map<int,bool> &mp,string &temp){

    if(s.size()==temp.size()){

        ans.push_back(temp);

        return;

    }

    for(int i=0;i<s.size();i++){

        if(mp[i]){

            temp.push_back(s[i]);

            mp[i]=false;

            TP(s,ans,mp,temp);

            mp[i]=true;

            temp.pop_back();

        }

    }

}

vector<string> findPermutations(string &s) {

    vector<string> ans;

    int n=s.size();

    string temp;

    map<int,bool> mp;

    for(int i=0;i<s.size();i++) mp[i]=true;

    TP(s,ans,mp,temp);

    return ans;

}

115 views
0 replies
0 upvotes

Interview problems

java code|| 97% better || upvote

import java.util.* ;

import java.io.*; 

public class Solution {

    static void swap(char[]s,int i,int j)

    {

        char temp = s[i];s[i]=s[j];s[j]=temp;

    }

    static void solve(char[] s,List<String>ans,int pointer)

    {

        if(pointer==s.length)

        {

            ans.add(new String(s));

            return;

        }

        for(int i=pointer; i<s.length; ++i)

        {

            swap(s,i,pointer);

            solve(s, ans, pointer+1);

            swap(s,i,pointer);

        }

    }

    public static List<String> findPermutations(String s) {

        // Write your code here.

        List<String>ans=new ArrayList<>();

        solve(s.toCharArray(),ans,0);

        return ans;

    }

}

55 views
0 replies
1 upvote

Interview problems

C++ | Backtracking

#include <bits/stdc++.h>


void solve(string &s, string &perm, vector<string> &ans, int idx){
    //base case
    if(idx==s.size()){
        ans.push_back(perm);
        return;
    }


    for(int i=0; i<=perm.size(); i++){
        perm.insert(i, 1, s[idx]);
        solve(s, perm, ans, idx+1);
        perm.erase(i, 1);
    }
    


}
vector<string> findPermutations(string &s) {
    string perm;
    vector<string> ans;
    perm.push_back(s[0]);
    solve(s, perm, ans, 1);


    return ans;
}
66 views
0 replies
0 upvotes

Interview problems

Easy C++ solution|| RECURSION

#include <bits/stdc++.h> 

void solve(string &s, int i, vector<string>& str){

    if(i >= s.length()){

        str.push_back(s);

        return;

    }

 

    for(int k = i; k < s.length(); k++){

        swap(s[i], s[k]);

        solve(s, i+1, str);

        swap(s[i], s[k]);

    }

}

 

vector<string> findPermutations(string &s) {

    vector<string> str;

    solve(s,0, str);

 

    return str;

}

91 views
0 replies
0 upvotes

Interview problems

Java Simple Answer

import java.util.* ;

import java.io.*; 

public class Solution {

    public static List<String> findPermutations(String s) {

        // Write your code here.

         List<String> result = new ArrayList<>();

         helper(result, s, 0, "", new boolean[s.length()]);

 

         return result;

 

    }

 

    private static void helper( List<String> result, String s, int index,String temp,boolean vis[]){

        if (index==s.length()) {

             result.add(temp);

             return;

        }

 

        for (int i = 0; i < s.length(); i++) {

            if (vis[i]) {

                continue;

                

            }

            vis[i] = true;

            helper(result, s, index+1, temp+String.valueOf(s.charAt(i)), vis);

             vis[i] = false;

        }

    }

}

76 views
0 replies
0 upvotes

Interview problems

C++ Solution || All test case passed || Time Complexity: O(2 ^ n)

#include <bits/stdc++.h>

//function to solve the question recursively
void solve (int idx, string s, vector<string>& ans) {

    //base case
    if (idx >= s.size()) {
        ans.push_back(s);
        return;
    }

    string temp = s;

    for (int i = idx; i < s.size(); i++) {
        swap(s[idx], s[i]);
        solve(idx+1, s, ans);
        s = temp;
    }

    return;
}

vector<string> findPermutations(string &s) {

    vector<string> ans;
    solve(0, s, ans);

    return ans;
}
208 views
0 replies
1 upvote

Interview problems

Python Backtracking

from os import *
from sys import *
from collections import *
from math import *


def helper(s, i, n, prev, ans):
	if i == n:
		ans.append("".join(prev))
		return
	for j in range(n):
		if prev[j] == '0':
			prev[j] = s[i]
			helper(s, i+1, n, prev, ans)
			prev[j] = '0'

def findPermutations(s):
	ans = []
	n = len(s)
	prev = ['0']*n
	helper(s, 0, n, prev, ans)
	return ans

python

182 views
0 replies
1 upvote

Interview problems

Easy solution better than 98.66%

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

void getpermute(string a, int i, vector<string> &str)

{

    if (i == a.length() - 1)

    {

        str.push_back(a);

        return;

    }

    for (int j = i; j < a.length(); j++)

    {

        swap(a[i], a[j]);

        getpermute(a, i + 1, str);

        swap(a[i], a[j]);

    }

}

int main(void)

{

    string a;

    cin >> a;

    vector<string> str;

    int length = a.length();

    getpermute(a, 0, str);

    for (const auto &a : str)

    {

        cout << a << " ";

    }

}

452 views
0 replies
0 upvotes

Interview problems

Simple Python Solution

def findPermutations(s):

    string = list(s)

    n = len(string)

    res = []

 

    def backtrack(start):

        if start == n:

            res.append("".join(string))

            return

 

        for i in range(start, n):

            string[start], string[i] = string[i], string[start]  # Swap elements

            backtrack(start + 1)

            string[start], string[i] = string[i], string[start]  # Backtrack, restore original order

 

    backtrack(0)

 

    return res

 

117 views
0 replies
0 upvotes
Full screen
Console