Country: India
Interview Type: In-Person

Comment hidden because of low score. Click to expand.
2
of 2 vote

Solution Using Backtracking:

``````void stringPermute( char *Arr, int idx, int N ) {
if ( N == idx )
cout << Arr ;
else {
for ( int j = idx; j <= N; j++ ) {
swap( (Arr+idx), (Arr+j) ) ;
stringPermute( Arr, idx+1, N ) ;
//Now Bactrack
swap( (Arr+idx), (Arr+j) ) ;
}
}
}``````

O(N*N!) Runtime

Comment hidden because of low score. Click to expand.
0

It doesn't looks like DP approach. If I misunderstood can you please explain the code in context with DP?

Comment hidden because of low score. Click to expand.
0

Yes, its not DP{My Bad}. Its recursive(backtracking) solution.
For Non-recursive solution can refer to Donald Knuth approach.
stackoverflow.com/questions/361/generate-list-of-all-possible-permutations-of-a-string

``````def nextPermutation(perm):
k0 = None
for i in range(len(perm)-1):
if perm[i]<perm[i+1]:
k0=i
if k0 == None:
return None

l0 = k0+1
for i in range(k0+1, len(perm)):
if perm[k0] < perm[i]:
l0 = i

perm[k0], perm[l0] = perm[l0], perm[k0]
perm[k0+1:] = reversed(perm[k0+1:])
return perm

perm=list("12345")
while perm:
print perm
perm = nextPermutation(perm)``````

Comment hidden because of low score. Click to expand.
1
of 1 vote

We can achieve it using recursion. We will place every letter in input as first letter and append it with every combination of remaining letters.
e.g. "abc" is input
The "a" is first element & combinations of other letters are "bc","cb". So complete combinations are "abc","acb".
The "b" is first element & combinations of other letters are "ac","ca". So complete combinations are "bac","bca".
The "c" is first element & combinations of other letters are "ab","ba". So complete combinations are "cab","cba".

So complete combinations are "abc","acb","bac","bca","cab","cba".

``````import java.util.ArrayList;

public class FindCombinaitons {

public static void main(String[] args) {
ArrayList<String> outputList =   findCombinations("abc");
System.out.println(outputList);

}
public static ArrayList<String>   findCombinations(String inut){
ArrayList<String> combinations = new ArrayList<>();
if(inut.length()<=0) return null;
if(inut.length()==1) {
return combinations;
}

for(int i =0;i<inut.length();i++){
char ch  = inut.charAt(i);
String firstPart =  inut.substring(0,i) ;
String secondPart = inut.substring(i+1);
//System.out.println("i="+i+" firstPart="+firstPart + " secondPart="+secondPart);
ArrayList<String> tempList= findCombinations(firstPart+secondPart);
for(String s:tempList){
}
}
return combinations;
}
}``````

Above java code can be further optimized using StringBuffer etc. but I have not used here so that users of other language will also understand it quickly.

Comment hidden because of low score. Click to expand.
0

some flaws are there for test cases like "ccc" or "abcc"

Comment hidden because of low score. Click to expand.
0

@tony To avoid duplicates; we need to check if character is already considered as first character.
So I maintain a set of characters. Before considering that character as first character; I add it into set. If addition is not successful then it means it is already considered. So I skip characters.

``````package stringsequennce;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class FindCombinaitons {

public static void main(String[] args) {
ArrayList<String> outputList =   findCombinations("abca");
System.out.println(outputList);

}
public static ArrayList<String>   findCombinations(String inut){
ArrayList<String> combinations = new ArrayList<>();
if(inut.length()<=0) return null;
if(inut.length()==1) {
return combinations;
}

for(int i =0;i<inut.length();i++){
char ch  = inut.charAt(i);
String firstPart =  inut.substring(0,i) ;
String secondPart = inut.substring(i+1);
//System.out.println("i="+i+" firstPart="+firstPart + " secondPart="+secondPart);
ArrayList<String> tempList= findCombinations(firstPart+secondPart);
for(String s:tempList){
}
}
}
return combinations;
}
}``````

Outpur for abca is

``````[abca, abac, acba, acab, aabc, aacb,
baca, baac, bcaa,
caba, caab, cbaa]``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

Logic :-
1> For each character of a string as the starting point
2> Loop the rest of the string till the string end.
3> Add the next char to the earlier string.

Code :-

public string Permute::Calculate(string _sofar, string _rest){
if(_rest==""){
return _sofar;
} else {
for(int _indexCounter = 0 ; _indexCounter <= _sofar.length();_indexCounter++){
_sofar += _sofar[_indexCounter];
_rest -= _sofar + _rest.substr(0,_indexCounter);
Calclate(_sofar,_rest);
}
}
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````#include <iostream>
#include <string>

void permuration(std::string prefix , std::string string){
if (string.length() == 0){
std::cout<<prefix<<std::endl;
return;
}
for (int i = 0 ; i < string.length() ; ++i){
permuration(prefix + string[i] , string.substr(0 , i) + string.substr(i+1 , string.length() - i+1));
}
}

int main(){
permuration("" , "abcd");
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

Comment hidden because of low score. Click to expand.
0

To avoid duplicates; we need to check if character is already considered as first character.
So I maintain a set of characters. Before considering that character as first character; I add it into set. If addition is not successful then it means it is already considered. So I skip characters.

``````import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class FindCombinaitons {

public static void main(String[] args) {
ArrayList<String> outputList =   findCombinations("abca");
System.out.println(outputList);

}
public static ArrayList<String>   findCombinations(String inut){
ArrayList<String> combinations = new ArrayList<>();
if(inut.length()<=0) return null;
if(inut.length()==1) {
return combinations;
}

for(int i =0;i<inut.length();i++){
char ch  = inut.charAt(i);
String firstPart =  inut.substring(0,i) ;
String secondPart = inut.substring(i+1);
//System.out.println("i="+i+" firstPart="+firstPart + " secondPart="+secondPart);
ArrayList<String> tempList= findCombinations(firstPart+secondPart);
for(String s:tempList){
}
}
}
return combinations;
}
}``````

Outpur for abca is

``````[abca, abac, acba, acab, aabc, aacb,
baca, baac, bcaa,
caba, caab, cbaa]``````

Output for "aaa" is "aaa"

Comment hidden because of low score. Click to expand.
0
of 0 vote

Basic idea is to keep a list of all permutations at index i, and insert the next character into every intervals of all strings in the list. No recursion is used.

``````public List<String> permutation(String str) {
if(str == null) {
return null;
}
List<String> per = new ArrayList<String>();
for(int i = 1; i < str.length(); i++) {
List<String> curr = new ArrayList<String>();
char c = str.charAt(i);
for(String s : per) {
for(int j = 0; j <= s.length(); j++) {
curr.add(s.substring(0, j) + c + s.substring(j));
}
}
per = curr;
}
return per;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public static List<char[]> findAllPermutations(char[] str) {
if (str == null) throw new NullPointerException();
List<char[]> permutations = new ArrayList<char[]>();
for (char c : str) {
List<char[]> perms = new ArrayList<char[]>();
for (char[] a : permutations) {
for (int i = 0; i < a.length; i++) {
char[] clone = a.clone();
if (clone[i] == '\u0000') {
clone[i] = c;
}
}
}
permutations = perms;
}
return permutations;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````package string;

import java.util.HashSet;
import java.util.Set;

public class AllPossiblePermutations {

static Set<String> set = new HashSet<String>();

public static void allPossibleCominations(String prefix , String str) {

int n = str.length();
if(n==0)  {
}
else {

//	System.out.println(str);
for(int i=0;i<n;i++) {

allPossibleCominations(prefix+str.charAt(i), str.substring(0,i)+str.substring(i+1,n));
}
}

}

public static void main(String[] args) {

allPossibleCominations("", "12	");
for(String s : set) {

System.out.println(s);
}
}

}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````st = []
def allPerm(prefix,str):

n = len(str)
if n==0:
st.append(prefix)
else:
st.append(prefix)
for i in range(0,n):
allPerm(prefix+str[i],str[:i]+str[i+1:])

str = "shuhail";
print(str[:2]+str[3:])

allPerm("","shu")
print(st)
print(set(st))``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.