...

/

Kth Smallest Number in M Sorted Lists (Medium)

Kth Smallest Number in M Sorted Lists (Medium)

Problem Statement

Given ‘M’ sorted arrays, find the K’th smallest number among all the arrays.

Example 1:

Input: L1=[2, 6, 8], L2=[3, 6, 7], L3=[1, 3, 4], K=5
Output: 4
Explanation: The 5th smallest number among all the arrays is 4, this can be verified from 
the merged list of all the arrays: [1, 2, 3, 3, 4, 6, 6, 7, 8]

Example 2:

Input: L1=[5, 8, 9], L2=[1, 7], K=3
Output: 7
Explanation: The 3rd smallest number among all the arrays is 7.

Try it yourself

Try solving this question here:

import java.util.*;
class KthSmallestInMSortedArrays {
public static int findKthSmallest(List<Integer[]> lists, int k) {
// TODO: Write your code here
return -1;
}
public static void main(String[] args) {
Integer[] l1 = new Integer[] { 2, 6, 8 };
Integer[] l2 = new Integer[] { 3, 6, 7 };
Integer[] l3 = new Integer[] { 1, 3, 4 };
List<Integer[]> lists = new ArrayList<Integer[]>();
lists.add(l1);
lists.add(l2);
lists.add(l3);
int result = KthSmallestInMSortedArrays.findKthSmallest(lists, 5);
System.out.print("Kth smallest number is: " + result);
}
}

Solution #

This problem follows the K-way merge pattern and we can follow a similar approach as discussed in Merge K Sorted Lists.

We can start merging all the arrays, but instead of inserting numbers into a merged list, we will keep count to see how many elements have been inserted in ...