top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Given an active stream of sorted arrays, how would you merge them efficiently?

+3 votes
445 views

Given an active stream of sorted arrays, how would you merge them efficiently?
C or Java code would be helpful?

posted Nov 16, 2015 by Saif Khanam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Use min heap to hold M values from M sorted arrays, O(N*log M), N total number of elements

static class Row<T> {
        Iterator<T> aRow;
        T currentValue;

        public Row(Iterator<T> aRow) {
            this.aRow = aRow;
            // currentValue is undefined
        }

        T getV() {return currentValue ;}

        boolean advance() {
            if (aRow.hasNext()) {
                currentValue = aRow.next();
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String toString() {
            return  currentValue + ":" + aRow.hasNext();

        }
    }
    @SafeVarargs
    static <T extends Comparable<T>> void merge(Consumer<T> downStream,
                                                Collection<T> ... sources) {

        PriorityQueue<Row<T>> heap = new PriorityQueue<>(sources.length,
                Comparator.comparing(Row::getV));

        for (Collection<T> it : sources) {

            Row<T> row = new Row<>(it.iterator());
            // row has any data?
            if (row.advance()) {
                heap.add(row);
            }
        }

        while(! heap.isEmpty()) {
            Row<T> row = heap.remove();
            downStream.accept(row.getV());

            // row has more data ?
            if (row.advance()) {
                heap.add(row);
            }
        }
    }

    public static void main(String[] args) {

        List<Integer> l1 = Arrays.asList(1,3, 6, 10);
        List<Integer> l2 = Arrays.asList(3,3, 10, 20);
        List<Integer> l3 = Arrays.asList(1,1, 3);
        List<Integer> l4 = Collections.emptyList();

        merge(System.out::println, l1, l2, l3, l4);
    }
answer Nov 17, 2015 by Mohammed Hussain
Similar Questions
+3 votes

Input:
[1 7 15 29 11 9]

Output:
[9 15] [1 7 11 29]

Average of first part: (15+9)/2 = 12,
Average of second part: (1 + 7 + 11 + 29) / 4 = 12

+5 votes

Given an unsorted array, find the max length of subsequence in which the numbers are in incremental order.

For example: If the input array is {7, 2, 3, 1, 5, 8, 9, 6}, a subsequence with the most numbers in incremental order is {2, 3, 5, 8, 9} and the expected output is 5.

+2 votes

1,1,2,2,2,6,6,6,7,7,7,7,7,7,7,8,8,9,9,9

Example:
Input = 1 Output=0 (First index of 1).
Input = 2 Output=2 (First index of 2).
Input = 6 Output= 5 (First index of 6).
Input = 7 Output= 8 (First index of 7).
Input = 8 Output=15 (First index of 8).
Input = 9 Output=17 (First index of 9).

...