Amazon Interview Question
SDE-3sCountry: United States
Interview Type: In-Person
val l1 = List('a') //> l1 : List[Char] = List(a)
val l2 = List('b') //> l2 : List[Char] = List(b)
val l3 =List('a', 'b') //> l3 : List[Char] = List(a, b)
val l4 =List('d') //> l4 : List[Char] = List(d)
def f (ls:List[Char], rs:List[Char]):List[List[Char]] = (ls, rs) match {
case (Nil,_) => rs::Nil
case (_,Nil) => ls::Nil
case (x::xs, y::ys) => (f(xs,rs) map (word => x::word)) ++ (f(ls,ys) map (word => y::word))
} //> f: (ls: List[Char], rs: List[Char])List[List[Char]]
f(l1,l2) //> res0: List[List[Char]] = List(List(a, b), List(b, a))
f(l3,l4) //> res1: List[List[Char]] = List(List(a, b, d), List(a, d, b), List(d, a, b))
Javascript solution
function perm(str1, str2, newArr, m, n, i) {
// Base case: If all characters of str1 and str2 have been
// included in output string, then print the output strin
if (m == 0 && n == 0) {
console.log(newArr)
return;// base condition
}
// If some characters of str1 are left to be included, then
// include the first character from the remaining characters
// and recur for rest
if (m !== 0) {
newArr[i] = str1.charAt(0);
perm(str1.substring(1), str2, newArr, m - 1, n, i + 1);
}
// If some characters of str2 are left to be included, then
// include the first character from the remaining characters
// and recur for rest
if (n !== 0) {
newArr[i] = str2.charAt(0);
perm(str1, str2.substring(1), newArr, m, n - 1, i + 1);
}
}
var str1 = "ab", str2 = "cd", i = 0;
perm(str1, str2, [], str1.length, str2.length, i);
- lalat.nayak March 17, 2017