Facebook Interview Question for Software Developers


Country: United States




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

Using java, this code should work,

int max = -1;
for (ArrayList<Integer> i : mulList)
    max = (max < i.size()) ? i.size() : max;
tmp = new ArrayList<>();
for (int j = 0; j < max; j++)
    for (ArrayList<Integer> i : mulList)
        try {
            tmp.add(i.get(j));
        }
        catch (IndexOutOfBoundsException e) {}
System.out.println(tmp.toString());

- PeyarTheriyaa April 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Such a poor style of code..

- Raaj July 13, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

instead do like this

private static List<Integer> interleavedListSimple(List<List<Integer>> lists) {

        List<Integer> interleaveList = new ArrayList<>();

        int maxSize = 0;

        for (List<Integer> list : lists)
            maxSize = Math.max(maxSize, list.size());

        int index = 0;
        while (index < maxSize) {
            for (int i = 0; i < lists.size(); i++) {
                if (index < lists.get(i).size()) {
                    interleaveList.add(lists.get(i).get(index));
                }
            }
            index++;
        }


        return interleaveList;
    }

- nitinguptaiit July 13, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Solution in Scala using transpose:

object InterleaveArrays {
  def main(args: Array[String]): Unit = {
    val list1 = List(1,2,3)
    val list2 = List(9,0)
    val list3 = List(5)
    val list4 = List(-4, -5, -2, -3, -1)

    println(getInterleaved(list1, list2, list3, list4))
  }

  def transpose[A](xs: List[List[A]]): List[List[A]] = xs.filter(_.nonEmpty) match {
    case Nil    =>  Nil
    case ys: List[List[A]] => ys.map{ _.head }::transpose(ys.map{ _.tail })
  }

  def getInterleaved(lists : List[Int]*) : List[Int] = {
    transpose(lists.toList).flatten
  }
}

// prints List(1, 9, 5, -4, 2, 0, -5, 3, -2, -3, -1)

- guilhebl April 18, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

$input = [[1,2,3], [9, 0], [5], [-4,-5,-2,-3,-1]]; 

$maxlength = 0;
$output = array();

foreach($input as $list){
    if(count($list) > $maxlength){
        $maxlength = count($list);
    }
}

for($i = 0; $i < $maxlength; $i++){
     for($k = 0; $k < count($input); $k++){
         if(isset($input[$k][$i])){
             $output[] = $input[$k][$i];
         }
     }
}

print_r($output);

- Kris April 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

<?php

$input = [[1,2,3], [9, 0], [5], [-4,-5,-2,-3,-1]]; 

$maxlength = 0;
$output = array();

foreach($input as $list){
    if(count($list) > $maxlength){
        $maxlength = count($list);
    }
}

for($i = 0; $i < $maxlength; $i++){
     for($k = 0; $k < count($input); $k++){
         if(isset($input[$k][$i])){
             $output[] = $input[$k][$i];
         }
     }
}

print_r($output);

- Kris April 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private List<Integer> interleaved( List<List<Integer>> listOfLists ) {
        List<Integer> list = new ArrayList<>();
        int size = listOfLists.size();
        int max = listOfLists.stream().mapToInt( s -> s.size() ).max().getAsInt();

        for ( int j = 0; j < max; j++ ) {
            for ( int i = 0; i < size; i++ ) {
                if (listOfLists.get( i ).size() > j) {
                    list.add( listOfLists.get( i ).get( j ) );
                }
            }
        }
        return list;
    }

- alltej April 20, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private List<Integer> interleaved( List<List<Integer>> listOfLists ) {
        List<Integer> list = new ArrayList<>();
        int size = listOfLists.size();
        int max = listOfLists.stream().mapToInt( s -> s.size() ).max().getAsInt();

        for ( int j = 0; j < max; j++ ) {
            for ( int i = 0; i < size; i++ ) {
                if (listOfLists.get( i ).size() > j) {
                    list.add( listOfLists.get( i ).get( j ) );
                }
            }
        }
        return list;
    }

- alltej April 20, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

vector<int> interleave(const vector<vector<int>>& input) {
    vector<int> result;
    int index = 0;
    int maxSize = INT_MIN;
    
    for (auto i : input) {
        maxSize = max(maxSize, (int)i.size());
    }
    
    while (index < maxSize) {
        for (int i = 0; i < input.size(); i++) {
            if (index >= input[i].size())
                continue;
            result.push_back(input[i][index]);
        }
        index++;
    }
    return result;
}

- sue April 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int[] interleaveLists(List<List<Integer>> ll){
    	if(ll == null)
    			return null;
    	int listLength = 0;
    	int total = 0;
    	for(List<Integer> list : ll){
    		if(list == null)
    			continue;
    		listLength = Math.max(list.size(), listLength);
    		total += list.size();
    	}
    	int[] result = new int[total];
    	int index = 0;
    	for(int i = 0; i < listLength; ++i){
    		for(List<Integer> list : ll){
    			if(list == null)
    				continue;
    				if(i < list.size()){
    					result[index++] = list.get(i);
    				}
    		}
    	}
    	return result;
    }

- popeye May 04, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int[] interleaveLists(List<List<Integer>> ll){
    	if(ll == null)
    			return null;
    	int listLength = 0;
    	int total = 0;
    	for(List<Integer> list : ll){
    		if(list == null)
    			continue;
    		listLength = Math.max(list.size(), listLength);
    		total += list.size();
    	}
    	int[] result = new int[total];
    	int index = 0;
    	for(int i = 0; i < listLength; ++i){
    		for(List<Integer> list : ll){
    			if(list == null)
    				continue;
    				if(i < list.size()){
    					result[index++] = list.get(i);
    				}
    		}
    	}
    	return result;
    }

- popeye May 04, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//C++
void interleave(vector<vector<int>> grid)
{
	int m = grid.size();
	int n = 0;
	
	for (int i = 0; i < m; i++)
		n = max(n, grid[i].size());
	vector<int> result;
	result.reserve(m*n);
	for (int j = 0; j < n; j++)
		for (int i = 0; i < m; i++)
			if (j < grid[i].size())
				result.push_back(grid[i][j]);
	for (auto i:result)
		cout << i << " ";
}

- aman.bansal4u May 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

### python
def interleave(ll):
    out = []
    while all_sublists(ll):
        for l in ll:
            if l:
                out.append(l.pop(0))
    return out

def all_sublists(ll):
    for l in ll:
        if l:
            return True
    return False

- slack0 May 23, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static List<Integer> mergeIntervals(final int[][] input) {

    int max = 0;
    final List<Integer> temp = new ArrayList<>();

    for (final int[] array : input) {
      if (array.length > max) {
        max = array.length;
      }
    }

    for (int k = 0; k < max; k++) {
      for (int j = 0; j < input.length; j++) {
        if (k < input[j].length) {
          temp.add(input[j][k]);
        }
      }
    }
    return temp;
  }

- Anonymous May 28, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// using java 
public static List<Integer> mergeIntervals(final int[][] input) {

    int max = 0;
    final List<Integer> temp = new ArrayList<>();

    for (final int[] array : input) {
      if (array.length > max) {
        max = array.length;
      }
    }

    for (int k = 0; k < max; k++) {
      for (int j = 0; j < input.length; j++) {
        if (k < input[j].length) {
          temp.add(input[j][k]);
        }
      }
    }
    return temp;
  }

- Abereham May 28, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def interleave_lists(ar):
    result = []
    max_length = 0
    for i in ar:
        max_length = max(max_length,len(i))

    for _ in range(max_length):
        for i in ar:
            if len(i) > 0:
                result.append(i.pop(0))
    return result

- Anonymous May 30, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I received this question in Feb 2018. I was told that there could be an undefined amount of arrays in the array so [1,[2,[3,4,5]],6,[7,8],9] was a possible input. Also that you didn't know the if the next element was a number so I wrote it in java as:

private ArrayList<Number> printList(ArrayList<Object> input){
	ArrayList<Number> output = new ArrayList();
	for(Object o: input){
		if(o instanceof Number)
			output.add(o);
		else if (o instance of ArrayList)
			output.addAll(printList(o));
	}
	return output;
}

- Stefan June 21, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my solution

int[][] input = { { 1, 2, 3 }, { 0, 9 }, { 5 }, { 4, 6, 7, 8 } };
//	     expected out put is [1,0,5,4,2,9,7,3,7,8]
		// int[] output = new int[];
		ArrayList<Integer> output = new ArrayList();
		int j = 0;
		while (j < input.length) {
			for (int i = 0; i < input.length; i++) {
				int[] arrayAtindex = input[i];
				if (j < arrayAtindex.length) {
					output.add(arrayAtindex[j]);

				}
			}
			j++;
		}
		System.out.println("output===>" + output);

- Sravani Cheripalli July 27, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private void getInterleaveList() {
		int[][] input = { { 1, 2, 3 }, { 0, 9 }, { 5 }, { 4, 6, 7, 8 } };
//	     expected out put is [1,0,5,4,2,9,7,3,7,8]
		// int[] output = new int[];
		ArrayList<Integer> output = new ArrayList();
		int j = 0;
		while (j < input.length) {
			for (int i = 0; i < input.length; i++) {
				int[] arrayAtindex = input[i];
				if (j < arrayAtindex.length) {
					output.add(arrayAtindex[j]);
				}
			}
			j++;
		}
		System.out.println("output===>" + output);
	}

- Sravani Cheripalli July 27, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private void getInterleaveList() {
int[][] input = { { 1, 2, 3 }, { 0, 9 }, { 5 }, { 4, 6, 7, 8 } };
// expected out put is [1,0,5,4,2,9,7,3,7,8]
// int[] output = new int[];
ArrayList<Integer> output = new ArrayList();
int j = 0;
while (j < input.length) {
for (int i = 0; i < input.length; i++) {
int[] arrayAtindex = input[i];
if (j < arrayAtindex.length) {
output.add(arrayAtindex[j]);
}
}
j++;
}
System.out.println("output===>" + output);
}

- Sravani Cheripalli July 27, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Solution {
  public static void main(String[] args) {

    // test case
    int[][] input = {{1,2,3}, {9, 0}, {5}, {-4,-5,-2,-3,-1}};

    int[] out = new int[input[0].length + input[1].length + input[2].length + input[3].length];

    out = interleaveList(input);
    for (int i = 0; i < out.length; i++)
      System.out.print(out[i] + " ");
  }
  
  static public int[] interleaveList(int[][] in) {
    
    // get max_len to cover all rows
    int max_len = 0;
    int size_all = 0; // size for all elements
    for (int i = 0; i < in.length; i++) {
      if (in[i].length > max_len)
        max_len = in[i].length;
      size_all += in[i].length;
    }
    
    int[] out = new int[size_all];
    int k = 0;
    // interleave in the loop
    for (int i = 0; i < max_len; i++) {
      for (int j = 0; j < in.length; j++) {
        if (i < in[j].length) {
          out[k++] = in[j][i];
        }
      }
    }
    
    return out;
  }
}

- CJ September 18, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

x = [[1,2,3],[5,6],[5],[-3,-4,-5,-6,-7]]
ans=[]

for j in range(len(x)):
out=[]
for i in x:
if i:
out.append(i.pop(0))
print(out)
ans.extend(out)

print(ans)

- Adi_ November 06, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

x = [[1,2,3],[5,6],[5],[-3,-4,-5,-6,-7]]
ans=[]

for j in range(len(x)):
    out=[]
    for i in x:
        if i:
            out.append(i.pop(0))
    print(out)
    ans.extend(out)

print(ans)

- Adi_ November 06, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class InterleavedList {

    static class Helper {
        public int listIndex = 0;
        public int selfIndex = 0;

        public Helper(int listIndex) {
            this.listIndex = listIndex;
        }

        @Override
        public String toString() {
            return "{" +
                    "listIndex=" + listIndex +
                    ", selfIndex=" + selfIndex +
                    '}';
        }
    }

    public static void main(String args[]) {

        List<List<Integer>> input = new ArrayList<>();

        List<Integer> one = new ArrayList<>();
        one.add(1);
        one.add(2);
        one.add(3);

        List<Integer> two = new ArrayList<>();
        two.add(9);
        two.add(0);

        List<Integer> three = new ArrayList<>();
        three.add(5);


        List<Integer> four = new ArrayList<>();
        four.add(-4);
        four.add(-5);
        four.add(-2);
        four.add(-3);
        four.add(-1);

        input.add(one);
        input.add(two);
        input.add(three);
        input.add(four);


        System.out.println(interleavedList(input));

    }


    private static List<Helper> getIndexList(int totalLists) {
        List<Helper> helpers = new ArrayList<>(totalLists);

        for (int i = 0; i < totalLists; i++) {
            helpers.add(new Helper(i));
        }

        return helpers;
    }

    private static List<Integer> interleavedList(List<List<Integer>> input) {

        int totalLists = input.size();

        //We use this list to iterate over input
        List<Helper> helpers = getIndexList(totalLists);
        int x = totalLists;

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

        //We remove all the helper once their corresponding list exhaust


        while (true) {
            ListIterator<Helper> listIterator = helpers.listIterator();
            while (listIterator.hasNext()) {

                Helper h = listIterator.next();

                //get the inner list by listIndex
                List<Integer> inner = input.get(h.listIndex);

                if (h.selfIndex < inner.size()) {
                    result.add(inner.get(h.selfIndex++));
                } else {
                    //If all element traversed, remove it for next iteration
                    listIterator.remove();
                }

            }

            if (helpers.isEmpty())
                break;

        }


        return result;

    }
}

- nitinguptaiit April 02, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is very easy to understand; and has performance boost if one of the list size is >>> then other

- nitinguptaiit April 02, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Another version of easy code ;

private static List<Integer> interleavedListSimple(List<List<Integer>> lists) {

        List<Integer> interleaveList = new ArrayList<>();

        int maxSize = 0;

        for (List<Integer> list : lists)
            maxSize = Math.max(maxSize, list.size());

        int index = 0;
        while (index < maxSize) {
            for (int i = 0; i < lists.size(); i++) {
                if (index < lists.get(i).size()) {
                    interleaveList.add(lists.get(i).get(index));
                }
            }
            index++;
        }


        return interleaveList;
    }

- nitinguptaiit July 13, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Nearly optimal:

def merge_list_of_list( list_of_lists ){
    iterators = list( list_of_lists ) as { $.o.iterator }
    final_merge_list = list( )
    added = true 
    while ( added ){
        added = false 
        for ( it : iterators ){
            added = it.hasNext 
            if ( added ){
                final_merge_list += it.next // done 
            }
        }
    }
    final_merge_list // return 
}

- NoOne April 17, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

List<Integer> interleave(List<List<Integer>> items){
     if(items==null) return null ;
     int size=items.size();
     if(size==1) return items.get(0);
     List<Integer> res = new ArrayList<>();
     int idx=0;
     boolean hasNext=true;
     while(hasNext) {
         hasNext=false;
         for(List<Integer> list: items) {
             if(idx <list.size() ) {
                 res.add(list.get(idx));
                 hasNext=true;
             }
         }
         idx++;
     }
     return res;
   }

- Nitu October 12, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

and
public class InterleaveList {
    /**
     * Interleave list of lists in Java
     * Example:
     * input = [[1,2,3], [9, 0], [5], [-4,-5,-2,-3,-1,5,2,234,2,24,24,4]];
     * output = [1,9,5,-4,2,0,-5,3,-2,-3,-1]
     */

    private static int[] findInterleaveList(int[][] arr) {

        List<Integer> interleaveList = new ArrayList<>();

        boolean shouldVisit = true;

        int index = 0;
        while (shouldVisit) {
            for (int i = 0; i < arr.length; i++) {
                if (index < arr[i].length) {
                    interleaveList.add(arr[i][index]);
                    shouldVisit = true;
                } else {
                    shouldVisit = false;
                }
            }
            index++;
        }


        int[] list = new int[interleaveList.size()];
        int position = 0;
        for (Integer integer : interleaveList) {
            list[position] = integer;
            position++;
        }

        return list;
    }

    public static void main(String[] args) {
        int[][] arr = {{1, 2, 3}, {9, 0}, {5}, {-4, -5, -2, -3, -1,5,2,234,2,24,24,4}};

        int[] output = findInterleaveList(arr);
        for (Integer interleave : output) {
            System.out.print(interleave);
            System.out.print("\t");
        }

    }
}

- Ajay April 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Code is wrong; this assume the last list is always greater then other list size;
try below input
[[1,2,3], [9,0],[5,9], [-4] ]

output you produce is
[1, 9, 5, -4, 2, 0, 9]
where as it should be
[1, 9, 5, -4, 2, 0, 9, 3]

- nitinguptaiit July 13, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

here is the correct code

private static List<Integer> interleavedListSimple(List<List<Integer>> lists) {

        List<Integer> interleaveList = new ArrayList<>();

        int maxSize = 0;

        for (List<Integer> list : lists)
            maxSize = Math.max(maxSize, list.size());

        int index = 0;
        while (index < maxSize) {
            for (int i = 0; i < lists.size(); i++) {
                if (index < lists.get(i).size()) {
                    interleaveList.add(lists.get(i).get(index));
                }
            }
            index++;
        }


        return interleaveList;
    }

- nitinguptaiit July 13, 2019 | Flag


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