Facebook Interview Question for Solutions Engineers


Country: Israel
Interview Type: Phone Interview




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

You can implement this in O(K) time and space. The approach I did was store an array of size K with all values set to 0. This will store the index for the K-th list.

The hasNext() function can be implemented by iterating through K-lists and checking if at least one of the indices is less than N. The next() function can be implemented by iterating through the K indices, and taking the index with a minimum value. The index with the minimum value is then incremented by one.

class MyIterator:
  def __init__(self, lists):
    self.lists = lists
    self.listCount = len(lists)
    self.listLen = len(lists[0])

    self.indices = [0] * self.listCount

  def next(self):
    val = float('inf')
    idx = -1

    for i in range(self.listCount):
      index = self.indices[i]
      if index < self.listLen:
        current_val = self.lists[i][index]
        if current_val < val:
          val = current_val
          idx = i

    if idx >= 0:
      self.indices[idx] += 1

    return val

  def hasNext(self):
    for i in range(self.listCount):
      if self.indices[i] < self.listLen:
        return True
    return False

lists = [[1,5,7], [2,3,10],[4,6,9]]
it = MyIterator(lists)
while it.hasNext():
  print(it.next())

- Anonymous January 14, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class MyIterator{
PriorityQueue<Integer> pq=new PriorityQueue<>();
int [][]data=null;
int []k=null;
public MyIterator(int [][] data) {
this.data=data;
k=new int[data.length];
this.preProcess(data);
}
int next(){
int tmp=pq.remove();
this.postProcess(tmp);
return tmp;

}
boolean hashNext(){
return pq.isEmpty();

}
public void preProcess(int [][]data){
for (int i = 0; i < k.length; i++) {
pq.add(data[i][k[i]]);
}
}
public void postProcess(int removedData){
for (int i = 0; i < k.length; i++) {
if(k[i]<data[i].length && data[i][k[i]]==removedData){
k[i]=k[i]+1;
if(k[i]<data[i].length){
pq.add(data[i][k[i]]);
}
return;
}
}
}
}
public class IteratorInKSortedArray {

public static void main(String[] args) {
int [][]in={
{1,5,7},
{2,3,10},
{4,6,9}
};


MyIterator itr=new MyIterator(in);
while(!itr.hashNext()){
System.out.print(itr.next()+" ");
}

}

}

- Achyut January 15, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class MyIterator{
PriorityQueue<Integer> pq=new PriorityQueue<>();
int [][]data=null;
int []k=null;
public MyIterator(int [][] data) {
this.data=data;
k=new int[data.length];
this.preProcess(data);}
int next(){
int tmp=pq.remove();
this.postProcess(tmp);
return tmp;}
boolean hashNext(){
return pq.isEmpty();

}
public void preProcess(int [][]data){
for (int i = 0; i < k.length; i++) {
pq.add(data[i][k[i]]);
}}
public void postProcess(int removedData){
for (int i = 0; i < k.length; i++) {
if(k[i]<data[i].length && data[i][k[i]]==removedData){
k[i]=k[i]+1;
if(k[i]<data[i].length){
pq.add(data[i][k[i]]);
}
return;}}}}
public class IteratorInKSortedArray {

public static void main(String[] args) {
int [][]in={
{1,5,7},
{2,3,10},
{4,6,9}
};
MyIterator itr=new MyIterator(in);
while(!itr.hashNext()){
System.out.print(itr.next()+" ");
}}}

- Anonymous January 15, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use K length array and priority queue
class MyIterator{
PriorityQueue<Integer> pq=new PriorityQueue<>();
int [][]data=null;
int []k=null;
public MyIterator(int [][] data) {
this.data=data;
k=new int[data.length];
this.preProcess(data);
}
int next(){
int tmp=pq.remove();
this.postProcess(tmp);
return tmp;}
boolean hashNext(){
return pq.isEmpty();}
public void preProcess(int [][]data){
for (int i = 0; i < k.length; i++) {
pq.add(data[i][k[i]]);
}}
public void postProcess(int removedData){
for (int i = 0; i < k.length; i++) {
if(k[i]<data[i].length && data[i][k[i]]==removedData){
k[i]=k[i]+1;
if(k[i]<data[i].length){
pq.add(data[i][k[i]]);
}
return;}}}

- Achyut January 15, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use k length array and priority queue
in hasNext() - return queue is empty or not
in next() - remove from queue and increase index value from k length array accordingly

- Achyut January 15, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.ArrayList;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.lang.Comparable;
import java.util.List;
import static java.util.Arrays.*;


class MyIter<T extends Comparable> implements Iterator {
  class IterState implements Comparable<IterState> {
    private Iterator<T> iter;
    private T currVal;
    public IterState(Iterator<T> i) {
      iter = i;
      next();
    }

    public T getVal() { return currVal; }
    public boolean hasNext() { return iter.hasNext(); }
    public void next() {
      if (iter.hasNext()) {
        currVal = iter.next();
      } else {
        currVal = null;
      }
    }

    public int compareTo(IterState o) {
      return currVal.compareTo(o.getVal());
    }
  }

  private PriorityQueue<IterState> states;
  
  public MyIter(List<List<T>> listOfList) {
    states = new PriorityQueue<IterState>();
    for (List<T> l:listOfList) {
      Iterator<T> it  = l.iterator();
      if (it.hasNext()) {
        states.add(new IterState(it));
      }
    }
  }; 

  public T next() {
    IterState n = states.poll();
    T retval = n.getVal();
    // if there is more in the current list, then put it back in the queue
    if (n.hasNext()) {
      n.next();
      states.add(n);
    }
    return retval;
  };

  public boolean hasNext() {
    return !states.isEmpty();
  }
} 


class Main {
  private static <T extends Comparable> ArrayList toArray(List<List<T>> listOfList) {
    MyIter<T> i = new MyIter<T>(listOfList);
    ArrayList retval = new ArrayList();
    while (i.hasNext()) {
      retval.add(i.next());
    }
    return retval;
  }


  public static void main(String[] args) {
    System.out.println("Hello world!");

    ArrayList arr = toArray(asList(
      asList(1,3,5),
      asList(2,4,6),
      asList(7,9),
      asList(8),
      asList(0,10),
      asList()));
    
    for (Object i:arr) {
      System.out.println(i);
    }

    arr = toArray(asList());
    for (Object i:arr) {
      System.out.println(i);
    }

  }
}

- Dennis February 06, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.*;
import java.util.*;


public class Solution {

  public void testMyIterator() {
    Integer[][] inputData = new Integer[][] {{1,2,3,10},{},{-1,4,5}};
    
    MyIterator<Integer> it = new MyIterator<>(inputData);
    
    while(it.hasNext()) {
      System.out.println(it.next());
    } 
  }

  public static void main(String[] args) {
    Solution s = new Solution();
    s.testMyIterator();   
  }
  
  public class MyIterator<T extends Comparable<T>> {
    private T[][] data;
    private int[] nextElementIndexByArrayIndex;

    public MyIterator(T[][] data) {
      if(data == null) {
        throw new IllegalArgumentException("data can't be null");
      }

      nextElementIndexByArrayIndex = new int[data.length];

      for(int i = 0; i < data.length; i++) {
        nextElementIndexByArrayIndex[i] = 0;
      }

      this.data = data;
    }

    public T next() {
      if(!hasNext()) {
        return null;
      }

      T retval = null;

      int selectedArrayIndex = -1;
      int selectedElementIndex = -1;

      for(int i = 0; i < data.length; i++) {
        int elementIndex = nextElementIndexByArrayIndex[i];
        if(data[i].length <= elementIndex) {
          continue;
        }
        T toCompare = data[i][elementIndex];

        if(retval == null || retval.compareTo(toCompare) > 0) {
          retval = toCompare;
          selectedArrayIndex = i;
          selectedElementIndex = elementIndex;
        }
      }

      selectedElementIndex++;
      nextElementIndexByArrayIndex[selectedArrayIndex] = selectedElementIndex;

      return retval;
    }

    public boolean hasNext() {
      for(int i = 0; i < data.length; i++) {
        if(data[i].length > nextElementIndexByArrayIndex[i]) {
          return true;
        }
      }
      return false;
    }
  }
  
}

- Danilo February 15, 2020 | 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