Sunday, January 15, 2023

#codingexercise 

Merge K sorted Lists:

List<Integer> merge(List<List<Integer>> slices)

{

var result = new List<Integer> ();

while(slices.size() > 0) {            

              slices.sort(new ListComparator<List<Integer>>());

              while(slices.size() > 0 && slices[0].size() == 0) {

                        slices.remove(0);

              }

               If (slices.size() == 0) {

         return result;

}              

result.add(slices[0].removeAt(0));

}

return result.toList():

}

 

public class ListComparator<List<Integer>> implements Comparator<List<Integer>> {

        public int compare(List<Integer> l1, List<Integer> l2) {

                           if (l1 == null && l2 == null) return -1;

                           if (l1 == null) return -1;                        

                           if (l2 == null) return 1;

                           if (l1.size() == 0 && l2.size() == 0) return -1;

                           if (l1.size() == 0) return -1;

                           if (l2.size() == 0) return 1;

                          return l1.get(0).compareTo(l2.get(0));

        }

}

 

Test cases:

1.       Null, Null -> []

2.       Null, [] -> []

3.       [], Null -> []

4.       [],[] -> []

5.       [1],[] -> [1]

6.       [], [1] -> [1]

7.       [1],[1] -> [1, 1]

8.       [1],[2] -> [1, 2]

9.       [2],[1] -> [1,2]

10.   [1],[2,3] -> [1,2,3]

11.   [1,2],[3] -> [1,2,3]

12.   [1,2,3],[] -> [1,2,3]

13.   [1,3][2] -> [1,2,3]

14.   [],[1,2,3] -> [1,2,3]

15.   [1][2][3]->[1,2,3]

16.   [1][2],[3],[5][6]-> [1,2,3,5,6]

17.   [][][1,2,3]->[1,2,3]

18.   [][1,2,3][]->[1,2,3]

19.   [1,2][3,5,6][]->[1,2,3,5,6]

20.   [1,2][3][4,5][6]->[1,2,3,4,5,6]

21.   [1,2,3,4,5,6,7][]->[1,2,3,4,5,6,7]

Reference: previous post

No comments:

Post a Comment