Amazon Interview Question
Dev Leads Dev LeadsCountry: India
Interview Type: In-Person
It doesn't looks like DP approach. If I misunderstood can you please explain the code in context with DP?
Yes, its not DP{My Bad}. Its recursive(backtracking) solution.
For Non-recursive solution can refer to Donald Knuth approach.
Please refer below link:
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)
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) {
combinations.add(inut);
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){
combinations.add(ch+s);
}
}
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.
@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) {
combinations.add(inut);
return combinations;
}
Set<Character> alreadyConsidered = new HashSet<Character>();
for(int i =0;i<inut.length();i++){
char ch = inut.charAt(i);
if(alreadyConsidered.add(ch)) { // Add into set is successfull means it is not already considered
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){
combinations.add(ch+s);
}
}
}
return combinations;
}
}
Outpur for abca is
[abca, abac, acba, acab, aabc, aacb,
baca, baac, bcaa,
caba, caab, cbaa]
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);
}
}
}
#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");
}
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) {
combinations.add(inut);
return combinations;
}
Set<Character> alreadyConsidered = new HashSet<Character>();
for(int i =0;i<inut.length();i++){
char ch = inut.charAt(i);
if(alreadyConsidered.add(ch)) { // Add into set is successfull means it is not already considered
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){
combinations.add(ch+s);
}
}
}
return combinations;
}
}
Outpur for abca is
[abca, abac, acba, acab, aabc, aacb,
baca, baac, bcaa,
caba, caab, cbaa]
Output for "aaa" is "aaa"
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>();
per.add(str.substring(0, 1));
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;
}
public static List<char[]> findAllPermutations(char[] str) {
if (str == null) throw new NullPointerException();
List<char[]> permutations = new ArrayList<char[]>();
permutations.add(new char[str.length]);
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;
perms.add(clone);
}
}
}
permutations = perms;
}
return permutations;
}
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) {
set.add(prefix);
}
else {
// System.out.println(str);
set.add(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);
}
}
}
Solution Using Backtracking:
O(N*N!) Runtime
- R@M3$H.N September 28, 2014