The iron ML notebook
  • The iron data science notebook
  • ML & Data Science
    • Frequent Questions
      • Discriminative vs Generative models
      • Supervised vs Unsupervised learning
      • Batch vs Online Learning
      • Instance-based vs Model-based Learning
      • Bias-Variance Tradeoff
      • Probability vs Likelihood
      • Covariance vs Correlation Matrix
      • Precision vs Recall
      • How does a ROC curve work?
      • Ridge vs Lasso
      • Anomaly detection methods
      • How to deal with imbalanced datasets?
      • What is "Statistically Significant"?
      • Recommendation systems methods
    • Statistics
      • The basics
      • Distributions
      • Sampling
      • IQR
      • Z-score
      • F-statistic
      • Outliers
      • The bayesian basis
      • Statistic vs Parameter
      • Markov Monte Carlo Chain
    • ML Techniques
      • Pre-process
        • PCA
      • Loss functions
      • Regularization
      • Optimization
      • Metrics
        • Distance measures
      • Activation Functions
      • Selection functions
      • Feature Normalization
      • Cross-validation
      • Hyperparameter tuning
      • Ensemble methods
      • Hard negative mining
      • ML Serving
        • Quantization
        • Kernel Auto-Tuning
        • NVIDIA TensorRT vs ONNX Runtime
    • Machine Learning Algorithms
      • Supervised Learning
        • Support Vector Machines
        • Adaptative boosting
        • Gradient boosting
        • Regression algorithms
          • Linear Regression
          • Lasso regression
          • Multi Layer Perceptron
        • Classification algorithms
          • Perceptron
          • Logistic Regression
          • Multilayer Perceptron
          • kNN
          • Naive Bayes
          • Decision Trees
          • Random Forest
          • Gradient Boosted Trees
      • Unsupervised learning
        • Clustering
          • Clustering metrics
          • kMeans
          • Gaussian Mixture Model
          • Hierarchical clustering
          • DBSCAN
      • Cameras
        • Intrinsic and extrinsic parameters
    • Computer Vision
      • Object Detection
        • Two-Stage detectors
          • Traditional Detection Models
          • R-CNN
          • Fast R-CNN
          • Faster R-CNN
        • One-Stage detectors
          • YOLO
          • YOLO v2
          • YOLO v3
          • YOLOX
        • Techniques
          • NMS
          • ROI Pooling
        • Metrics
          • Objectness Score
          • Coco Metrics
          • IoU
      • MOT
        • SORT
        • Deep SORT
  • Related Topics
    • Intro
    • Python
      • Global Interpreter Lock (GIL)
      • Mutability
      • AsyncIO
    • SQL
    • Combinatorics
    • Data Engineering Questions
    • Distributed computation
      • About threads & processes
      • REST vs gRPC
  • Algorithms & data structures
    • Array
      • Online Stock Span
      • Two Sum
      • Best time to by and sell stock
      • Rank word combination
      • Largest subarray with zero sum
    • Binary
      • Sum of Two Integers
    • Tree
      • Maximum Depth of Binary Tree
      • Same Tree
      • Invert/Flip Binary Tree
      • Binary Tree Paths
      • Binary Tree Maximum Path Sum
    • Matrix
      • Set Matrix Zeroes
    • Linked List
      • Reverse Linked List
      • Detect Cycle
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
    • String
      • Longest Substring Without Repeating Characters
      • Longest Repeating Character Replacement
      • Minimum Window Substring
    • Interval
    • Graph
    • Heap
    • Dynamic Programming
      • Fibonacci
      • Grid Traveler
      • Can Sum
      • How Sum
      • Best Sum
      • Can Construct
      • Count Construct
      • All Construct
      • Climbing Stairs
Powered by GitBook
On this page

Was this helpful?

  1. Algorithms & data structures
  2. Linked List

Merge k Sorted Lists

PreviousMerge Two Sorted ListsNextString

Last updated 3 years ago

Was this helpful?

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    """
    k = num of lists
    N = total number of nodes
    """
    
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        return self.mergeKListsDivideAnConquer(lists)  # best solution

    def mergeKListsDivideAnConquer(
        self, 
        lists: List[Optional[ListNode]]
    ) -> Optional[ListNode]:
        """
        Time: O(N*log_2(k)) -> iterates the N nodes log_2(k) times
        Space: O(N) -> N stack calls
        """
        
        filtered_list = list(filter(lambda item: item is not None, lists))
        
        if len(filtered_list) == 0:
            return None
        
        return self.helper_mergeKListsDivideAnConquer(filtered_list)
    
    def helper_mergeKListsDivideAnConquer(
        self, 
        lists: List[Optional[ListNode]]
    ) -> Optional[ListNode]:
        
        if len(lists) == 1:
            return lists[0]
        
        if len(lists) % 2 != 0:  # if impair length 
            middle = int(len(lists) / 2)  # find middle
            return self.mergeTwoListsRecursive(  # apply the merge twice
                l1=self.mergeTwoListsRecursive(  # for the two halfs
                    l1=self.helper_mergeKListsDivideAnConquer(lists[:middle]), 
                    l2=self.helper_mergeKListsDivideAnConquer(lists[middle+1:])
                ),
                l2=lists[middle]  # and for the middle one
            )
        
        # find middle for pair list
        middle = int(len(lists) / 2)
        return self.mergeTwoListsRecursive(
            l1=self.helper_mergeKListsDivideAnConquer(lists[:middle]), 
            l2=self.helper_mergeKListsDivideAnConquer(lists[middle:])
        )

    
    def mergeKListsTwoByTwo(
        self, 
        lists: List[Optional[ListNode]]
    ) -> Optional[ListNode]:
        """
        Time: O(N*k) -> iterates the N nodes for the k lists
        Space: O(N) -> N stack calls
        """
        
        if len(lists) == 0:
            return None
        
        ordered = ListNode(-float("inf"))
        for l in lists:
            if l is not None:
                ordered = self.mergeTwoListsRecursive(l, ordered)
            
        return ordered.next
            
    def mergeTwoListsRecursive(
        self, 
        l1: Optional[ListNode], 
        l2: Optional[ListNode]
    ) -> Optional[ListNode]:
        """
        Time: O(N)
        Space: O(1) from variables + O(N) from stack calls => O(N)
        """
        
        merged = None
        curr = None
        
        if l1 is None:
            return l2
        elif l2 is None:
            return l1
        elif l1.val <= l2.val:
            curr = l1
            merged = self.mergeTwoListsRecursive(l1.next, l2)
        else:
            curr = l2
            merged = self.mergeTwoListsRecursive(l1, l2.next)
            
        curr.next = merged
        
        return curr
    
    def mergeKListsCompareOneByOne(
        self, 
        lists: List[Optional[ListNode]]
    ) -> Optional[ListNode]:
        """
        Time: O(N*k) -> find the smallest node for the k lists 
                        until all N nodes are visited
        Space: O(1) from variables + O(N) from stack calls => O(N)
        """
                
        node, index = self.findMinNode(lists)
        if node is None:
            return None
        
        merged = self.mergeKListsRecursive(
            lists[:index] + [node.next] +  lists[index+1:]
        )
        
        node.next = merged
        
        return node
    
    def findMinNode(
        self, 
        lists: List[Optional[ListNode]]
    ) -> Tuple[ListNode, int]:
        values = list(map(lambda node: node.val if node else None, lists))
        not_none_values = list(filter(lambda item: item is not None, values))
        
        if len(not_none_values) == 0:
            return None, -1
        
        min_value = min(not_none_values)
        min_index = values.index(min_value)
        
        return lists[min_index], min_index
https://leetcode.com/problems/merge-k-sorted-lists