Tutorialspoint
Problem
Solution
Submissions

Merge K Sorted Arrays into One Sorted Array

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to implement the MergeKSortedArrays function, which merges k sorted arrays into one sorted array. The function should take a jagged array (array of arrays) as input and return a single sorted array containing all elements from the input arrays.

Example 1
  • Input: arrays = [[1,4,5],[1,3,4],[2,6]]
  • Output: [1,1,2,3,4,4,5,6]
  • Explanation:
    • The input contains 3 sorted arrays:
    • [1,4,5], [1,3,4], and [2,6]
    • When merged, they form [1,1,2,3,4,4,5,6]
Example 2
  • Input: arrays = [[10,15,30],[12],[5,8,20,25]]
  • Output: [5,8,10,12,15,20,25,30]
  • Explanation:
    • The input contains 3 sorted arrays:
    • [10,15,30], [12], and [5,8,20,25]
    • When merged, they form [5,8,10,12,15,20,25,30]
Constraints
  • 1 ≤ k ≤ 10^4 (where k is the number of arrays)
  • 0 ≤ arrays[i].length ≤ 500
  • -10^4 ≤ arrays[i][j] ≤ 10^4
  • Each arrays[i] is sorted in ascending order
  • Time Complexity: O(n log k) where n is the total number of elements across all arrays
  • Space Complexity: O(n)
ArraysIBMAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider using a min-heap (priority queue) to efficiently merge the arrays
  • Keep track of which array each element came from
  • Maintain pointers to the current position in each array
  • Extract the minimum element from the heap, then add the next element from the same array
  • Use C#'s built-in PriorityQueue class or implement your own

Steps to solve by this approach:

 Step 1: Create a priority queue (min-heap) to keep track of the smallest elements
 Step 2: Initialize the heap with the first element from each array along with information about which array it came from
 Step 3: Extract the minimum element from the heap and add it to the result array
 Step 4: After extracting an element, add the next element from the same array to the heap
 Step 5: Repeat steps 3 and 4 until the heap is empty
 Step 6: Return the result array containing all elements in sorted order
 Step 7: Time complexity is O(n log k) where n is the total number of elements and k is the number of arrays

Submitted Code :