a
Amazon 87f
Facebook 45G
Google 42M
Microsoft 38🍎
Apple 25
Merge k Sorted Lists — Solution
The key insight is to avoid sorting all values from scratch. Instead, leverage the fact that individual lists are already sorted. The divide and conquer approach is optimal: merge lists pairwise until one remains. Time: O(n log k), Space: O(log k).
Common Approaches
✓
Brute Force - Collect All Values
⏱️ Time: O(n log n)
Space: O(n)
Traverse all k linked lists to collect every node value into an array. Sort the array and construct a new linked list from the sorted values.
Divide and Conquer
⏱️ Time: O(n log k)
Space: O(log k)
Recursively merge pairs of lists until only one remains. Use the efficient merge two sorted lists algorithm as the base operation.
Min Heap Approach
⏱️ Time: O(n log k)
Space: O(k)
Maintain a min heap of the current heads of all non-empty lists. Extract minimum, add to result, and push the next node from that list back to heap.
Brute Force - Collect All Values — Algorithm Steps
Step 1: Traverse all k lists and collect values
Step 2: Sort the collected values
Step 3: Create new linked list from sorted values
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Extract Values
Collect all node values from k lists
2
Sort Array
Sort the collected values
3
Build Result
Create new linked list from sorted array
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode {
int val;
struct ListNode* next;
};
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
struct ListNode* solution(struct ListNode** lists, int listsSize) {
if (lists == NULL || listsSize == 0) return NULL;
// Collect all values
int* values = malloc(10000 * sizeof(int));
int valueCount = 0;
for (int i = 0; i < listsSize; i++) {
struct ListNode* curr = lists[i];
while (curr) {
values[valueCount++] = curr->val;
curr = curr->next;
}
}
if (valueCount == 0) {
free(values);
return NULL;
}
// Sort values
qsort(values, valueCount, sizeof(int), compare);
// Create new linked list
struct ListNode* dummy = malloc(sizeof(struct ListNode));
dummy->val = 0;
dummy->next = NULL;
struct ListNode* curr = dummy;
for (int i = 0; i < valueCount; i++) {
curr->next = malloc(sizeof(struct ListNode));
curr->next->val = values[i];
curr->next->next = NULL;
curr = curr->next;
}
struct ListNode* result = dummy->next;
free(dummy);
free(values);
return result;
}
struct ListNode* arrayToList(int* arr, int size) {
if (size == 0) return NULL;
struct ListNode* head = malloc(sizeof(struct ListNode));
head->val = arr[0];
head->next = NULL;
struct ListNode* curr = head;
for (int i = 1; i < size; i++) {
curr->next = malloc(sizeof(struct ListNode));
curr->next->val = arr[i];
curr->next->next = NULL;
curr = curr->next;
}
return head;
}
void listToArray(struct ListNode* head, int* result, int* size) {
*size = 0;
while (head) {
result[(*size)++] = head->val;
head = head->next;
}
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char line[10000];
fgets(line, sizeof(line), stdin);
// Simple parsing for the specific input format
struct ListNode* lists[1000];
int listsSize = 0;
if (strstr(line, "[]") && !strstr(line, "[[]]")) {
listsSize = 0;
} else if (strstr(line, "[[]]")) {
lists[0] = NULL;
listsSize = 1;
} else {
// Parse nested arrays
char* p = line;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']') break;
if (*p == '[') {
char innerArray[1000] = {0};
int depth = 0;
char* start = p;
while (*p) {
if (*p == '[') depth++;
else if (*p == ']') depth--;
p++;
if (depth == 0) break;
}
strncpy(innerArray, start, p - start);
int arr[1000];
int arrSize;
parseArray(innerArray, arr, &arrSize);
lists[listsSize++] = arrayToList(arr, arrSize);
}
}
}
struct ListNode* resultHead = solution(lists, listsSize);
int result[10000];
int resultSize;
listToArray(resultHead, result, &resultSize);
printf("[");
for (int i = 0; i < resultSize; i++) {
if (i > 0) printf(",");
printf("%d", result[i]);
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n log n)
Collecting n values takes O(n), sorting takes O(n log n) where n is total nodes
n
2n
⚡ Linearithmic
Space Complexity
O(n)
Extra array stores all n node values
n
2n
✓ Linear Space
89.7K Views
Very HighFrequency
~25 minAvg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.