βš”οΈ
DSA Important Questions
  • πŸ˜‡README
  • πŸ”«Question List
  • πŸ§ͺFormula List
  • πŸ—’οΈ01 Array
    • βœ…Rotate Matrix
    • βœ…Max Sum Contiguous Subarray
    • Find Duplicate in Array
    • βœ…Merge Intervals
    • βœ…Spiral Order Matrix I
    • Repeat and Missing Number Array
    • βœ…Merge Overlapping Intervals
    • βœ…Set Matrix Zeros
    • βœ…Spiral Order Matrix II
    • Largest Number
    • First Missing Integer
    • βœ…Pascal Triangle
    • ⭐Max Distance
    • βœ…Wavy Array
    • Next Permutation
    • βœ…Min Steps in Infinite Grid
    • Flip
    • ⭐Find Permutation
    • ⭐Maximum Absolute Difference
    • ⭐Maximum Unsorted Subarray
    • Reorder Data in Log File
    • βœ…Make equal elements Array
  • βž•02 Math
    • βœ…Excel Column Number
    • ⭐Excel Column Title
    • ⭐Grid Unique Paths
    • ⭐Power Of Two Integers
    • βœ…Next Similar Number
    • ⭐k-th Permutation
  • πŸ”03 Binary Search
    • ⭐Median of Array
    • ⭐Square Root of Integer
    • ⭐Rotated Sorted Array Search
    • ⭐Matrix Median
    • Capacity To Ship Packages Within B Days
  • 🧡04 String
    • Implement StrStr
    • ⭐Integer to Roman
    • ⭐Roman to Integer
    • Length of Last Word
    • ⭐atoi
    • ⭐Valid IP Addresses
    • ⭐Compare Version Numbers
    • ⭐Longest Palindromic Substring
    • Count And Say
    • Reverse the String
    • Power of 2
    • 🚧KMP: Minimum Characters Required to Make a String Palindromic
    • ⭐Convert to Palindrome
    • Bulls and Cows
  • 1️⃣05 Bit Manipulation
    • Reverse Bits
    • Single Number
    • ⭐Divide Integers
    • ⭐Single Number II
    • ⭐Count Total Set Bits
    • ⭐Palindromic Binary Representation
  • ✌️06 Two Pointers
    • Merge Two Sorted Lists II
    • ⭐3 Sum
    • Remove Duplicates from sorted Array
    • ⭐Container With Most Water
    • Remove Element from Array
    • ⭐Max Continuous Series of 1s
    • Pair With Given Difference
    • ⭐Maximum Ones After Modification
  • πŸ”—07 Linked List
    • Swap List Nodes in Pairs
    • Rotate List
    • ⭐Reorder List
    • Merge Two Sorted Lists
    • Remove Duplicates from Sorted List
    • Add Two Numbers as Lists
    • Remove Nth Node from List End
    • ⭐List Cycle
    • Intersection of Linked Lists
    • ⭐Reverse Linked List II
    • Palindrome List
    • ⭐K reverse linked list
    • ⭐Reverse Alternate K Nodes
    • ⭐Kth Node From Middle
    • ⭐Sort Binary Linked List
    • ⭐Even Reverse
  • πŸ“š08 Stacks and Queues
    • ⭐Rain Water Trapping
    • Generate all Parentheses
    • ⭐Largest Rectangle in Histogram
    • ⭐Min Stack
    • Redundant Braces
    • Nearest Smaller Element
    • ⭐First non-repeating character in a stream of characters
    • βœ…Balanced Parantheses!
  • πŸ”™09 Backtracking
    • ⭐Kth Permutation Sequence
    • ⭐Combination Sum
    • Combination Sum II
    • ⭐NQueens
    • Combinations
    • ⭐Subsets II
    • Subset
    • Palindrome Partitioning
  • πŸ’±10 Hashing
    • ⭐Longest Consecutive Sequence
    • ⭐4 Sum
    • ⭐Anagrams
    • ⭐Points on the Straight Line
    • 2 Sum
    • ⭐Valid Sudoku
    • Copy List
    • Longest Substring Without Repeat
  • πŸ—»11 Heaps & Maps
    • Merge K Sorted Lists
    • ⭐LRU Cache
    • ⭐Inversions
    • Distinct Numbers in Window
  • 🌳12 Tree Data Structure
    • βœ…Inorder Traversal
    • ⭐Recover Binary Search Tree
    • ⭐Inorder Traversal of Cartesian Tree
    • ⭐Least Common Ancestor
    • ⭐Construct Binary Tree From Inorder And Preorder
    • Flatten Binary Tree to Linked List
    • Valid Binary Search Tree
    • βœ…Preorder Traversal
    • ⭐Binary Tree From Inorder And Postorder
    • Balanced Binary Tree
    • βœ…Sorted Array To Balanced BST
    • Symmetric Binary Tree
    • βœ…Postorder Traversal
    • ⭐Populate Next Right Pointers Tree
    • Identical Binary Trees
    • BST Iterator
    • ZigZag Level Order Traversal BT
    • Path Sum
    • Next Pointer Binary Tree
    • Min Depth of Binary Tree
    • Root to Leaf Paths With Sum
    • ⭐Kth Smallest Element in Tree
    • ⭐2-Sum Binary Tree
    • Vertical Order traversal of Binary Tree
    • ⭐Diagonal Traversal
    • Cousins in Binary Tree
    • Path to Given Node
    • Remove Half Nodes
    • Merge two Binary Tree
    • ⭐Burn a Tree
    • Nodes at Distance K
    • Vertical Sum of a Binary Tree
    • Covered / Uncovered Nodes
  • 13 Dynamic Programming
    • Ugly Number II
    • Coin Change
    • 0 - 1 Knapsack Problem
    • Permutation Coefficient
  • 14 Greedy Algorithm
    • ⭐Gas Station
    • ⭐Majority Element
    • ⭐Distribute Candy
    • ⭐Highest Product
    • Assign Mice to Holes
    • ⭐Meeting rooms
  • πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦15 Graph
    • Clone Graph
    • Word Search Board
    • ⭐Stepping Numbers
    • Black Shapes
    • Knight On Chess Board
    • ❌Smallest Multiple With 0 and 1
    • ⭐Commutable Islands
    • Possibility of finishing all courses given pre-requisites
    • ❌Valid Path
    • Cycle in Directed Graph
    • ❌Cycle in Undirected Graph
Powered by GitBook
On this page
  • 5 Approaches
  • Using Merge 2 Sorted List
  • Compare All and Choose Min​
  • Link all Linked List and Use Merge Sort
  • Notice Merge Function ​
  • Dividing k Linked Lists into 2
  1. 11 Heaps & Maps

Merge K Sorted Lists

PreviousLongest Substring Without RepeatNextLRU Cache

Last updated 2 years ago

5 Approaches

Approach
Time Complexity
Space Complexity

Using Merge 2 Sorted

List

Using k pointers

Link All List and Merge Sort

Divide and Conquer

Using Merge 2 Sorted List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
ListNode *merge2Lists(ListNode *A, ListNode *B) {
    ListNode *merged = new ListNode(-1);
    ListNode *mergedHead = merged;
    ListNode *ptr1 = A;
    ListNode *ptr2 = B;
    
    while(ptr1 && ptr2) {
        if(ptr1->val < ptr2->val) {
            merged->next = ptr1;
            ptr1 = ptr1->next;
        } else {
            merged->next = ptr2;
            ptr2 = ptr2->next;
        }
            
        merged = merged->next;
    }
    
    
    while(ptr1) {
        merged->next = ptr1;
        ptr1 = ptr1->next;
        merged = merged->next;
    }
    
    while(ptr2) {
        merged->next = ptr2;
        ptr2 = ptr2->next;
        merged = merged->next;
    }
    
    return mergedHead->next;    
}
ListNode* Solution::mergeKLists(vector<ListNode*> &A) {
    ListNode *merged = A[0];
    for(int i = 1; i < A.size(); i++) 
        merged = merge2Lists(merged, A[i]);
        
    return merged;
}

Accepted

Time Complexity: O(kn)O(kn)O(kn)​ where n nn​ is the number of elements in each list.

Space Complexity: O(1)O(1)O(1)

Compare All and Choose Min​

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
ListNode* Solution::mergeKLists(vector<ListNode*> &A) {
    ListNode *merged = new ListNode(-1);
    ListNode *mergedHead = merged;
    
    bool allNULL = false;
    while(true) {
        int i = 0;
        while(i < A.size() && !A[i]) 
            i++;
        
        if(i == A.size())
            break;
        
        int minNode = i;
        while(i < A.size()) {
            if(A[i] && A[i]->val < A[minNode]->val) {
                minNode = i;
                allNULL = false;
            }
            i++;
        }
        
        merged->next = A[minNode];
        
        A[minNode] = A[minNode]->next;
        merged = merged->next;
    }
    return mergedHead->next;
}

Accepted

Time Complexity: O(nk)O(nk)O(nk)​

Space Complexity: O(1)O(1)O(1)

Link all Linked List and Use Merge Sort

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
void link(ListNode *l1, ListNode *l2) {
    ListNode *ptr = l1;
    while(ptr -> next)
        ptr =  ptr -> next;
    
    ptr -> next = l2;
}

ListNode *getMid(ListNode *ll) {
    ListNode *slow = ll;
    ListNode *fast = ll;
    
    while(fast && fast->next && fast->next->next) {
        slow = slow->next;
        fast = fast->next->next;
    }
    
    return slow;
}

ListNode *merge(ListNode *l1, ListNode *l2) {
    if(!l1)
        return l2;
    
    if(!l2) 
        return l1;
        
    ListNode *head = (l1->val < l2->val) ? l1 : l2;
    while(l1 && l2)
        if(l1->val < l2->val) {
            ListNode* next = l1->next;
            if(!l1->next || l1->next->val >= l2->val) 
                l1->next = l2;            
            l1 = next;
        } else {
            ListNode *next = l2->next;
            if(!l2->next || l2->next->val > l1->val)
                l2->next = l1;
            l2 = next;
        }
    
    return head;
}

ListNode *mergeSort(ListNode *l1) {
    if(!l1 || !l1->next)
        return l1;
        
    ListNode *mid = getMid(l1);
    ListNode *l2 = mid->next;
    mid->next = NULL;
    l1 = mergeSort(l1);
    l2 = mergeSort(l2);
    return merge(l1, l2);
}

ListNode* Solution::mergeKLists(vector<ListNode*> &A) {
    ListNode *head = A[0];
    for(int i = 1; i < A.size(); i++)
        link(A[i - 1], A[i]); 
        
    return mergeSort(head);    
}

Accepted

Time Complexity: O(nlog⁑k)O(n \log k)O(nlogk)​

Space Complexity: O(1)O(1)O(1)

ListNode *merge(ListNode *l1, ListNode *l2) {
    if(!l1)
        return l2;
    
    if(!l2) 
        return l1;
        
    ListNode *head = (l1->val < l2->val) ? l1 : l2;
    while(l1 && l2)
        if(l1->val < l2->val) {
            ListNode* next = l1->next;
            if(!l1->next || l1->next->val >= l2->val)  // why >=? 
                l1->next = l2;            
            l1 = next;
        } else {
            ListNode *next = l2->next;
            if(!l2->next || l2->next->val > l1->val)
                l2->next = l1;
            l2 = next;
        }
    
    return head;
}

Dividing k Linked Lists into 2

  1. Divide the given KKK Linked Lists into two parts until single LL remains

  2. Backtrack and merge 2 Linked Lists at a time until is reached.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
ListNode *merge(ListNode *left, ListNode *right) {
    if(!left)   
        return right;
        
    if(!right)
        return left;
        
    ListNode *head = (left->val < right->val) ? left : right;
    while(left && right)
        if(left->val < right->val) {
            ListNode *next = left->next;
            if(!left->next || left->next->val >= right->val)
                left->next = right;
            
            left = next;
        } else {
            ListNode *next = right->next;
            if(!right->next || right->next->val > left->val)
                right->next = left;            
            right = next;
        }
    return head;
}
 
ListNode *DivideAndConquerMerge(vector<ListNode *> &A, int low, int high) {
    if(low >= high) 
        return A[low];
    
    int mid = low + ((high - low) >> 1);
    ListNode *left = DivideAndConquerMerge(A, low, mid);
    ListNode *right = DivideAndConquerMerge(A, mid + 1, high);
    
    return merge(left, right);    
}
ListNode* Solution::mergeKLists(vector<ListNode*> &A) {
    return DivideAndConquerMerge(A, 0, A.size() - 1);    
}

Accepted

Time Complexity: O(nlog⁑k)O(n\log k)O(nlogk)​

Space Complexity: O(1)O(1)O(1)​

​

​

Notice Merge Function ​

πŸ—»
O(nk)O(nk)O(nk)
O(1)O(1)O(1)
O(nk)O(nk)O(nk)
O(1)O(1)O(1)
O(nlog⁑n)O(n\log n)O(nlogn)
O(1)O(1)O(1)
O(nlog⁑k)O(n\log k)O(nlogk)
O(1)O(1)O(1)
⭐
Merge K Sorted Lists - InterviewBitInterviewBit
Logo
Discusses 5 Approaches