Amazon Interview Question for Dev Leads Dev Leads


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

- R@M3$H.N September 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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

- Anon September 28, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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)

- R@M3$H.N September 29, 2014 | Flag
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) {
			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.

- Kaushik Lele September 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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

- AlgoBaba September 28, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@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]

- Kaushik Lele October 03, 2014 | Flag
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);
}
}
}

- hprem991 September 29, 2014 | Flag Reply
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");
}

- GK September 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about "aaaa"?

- Alex September 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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"

- Kaushik Lele October 03, 2014 | Flag
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>();
	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;
}

- Belmen September 30, 2014 | Flag Reply
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[]>(); 
		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;
	}

- Guillaume October 02, 2014 | Flag Reply
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)  {
		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);
		}
	}

}

- shukad333 October 03, 2014 | Flag Reply
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))

- shukad333 October 03, 2014 | Flag Reply


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More