Merge K Sorted Lists in Java: Explanation & Practice

Merge multiple sorted lists into one

Problem summary

Write a program that merges k sorted lists into a single sorted list.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<List<Integer>> lists = Arrays.asList(
            Arrays.asList(1, 4, 7),
            Arrays.asList(2, 5, 8),
            Arrays.asList(3, 6, 9)
        ); // Test case 1
        
        // Merge into single sorted list
        // Print space-separated
    }
}

Expected output and test cases

  • Merged and sorted
    1 2 3 4 5 6 7 8 9
  • With duplicates
    1 1 2 2 3 3
  • Two lists
    1 2 3 4 5

Hints

  1. Use PriorityQueue for efficient merge
  2. Add first element of each list
  3. Track which list each element came from

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler