Skip to content

Instantly share code, notes, and snippets.

@GregoryMaks
Created February 20, 2026 11:28
Show Gist options
  • Select an option

  • Save GregoryMaks/4dc67b630871dbcb0d71a1b3fbf53920 to your computer and use it in GitHub Desktop.

Select an option

Save GregoryMaks/4dc67b630871dbcb0d71a1b3fbf53920 to your computer and use it in GitHub Desktop.
// Time: O(NxK)
// Space: O(NxK) - need to store the results somewhere
class Solution {
func mergeKLists(_ lists: [ListNode?]) -> ListNode? {
var tops = lists.compactMap { $0 ?? nil }
var resultRoot: ListNode?
var resultLast: ListNode?
while tops.count > 0 {
var pickIdx = 0
var val = Int.max
// search
for i in 0..<tops.count {
if tops[i].val < val {
pickIdx = i
val = tops[i].val
}
}
// save
let newNode = ListNode(tops[pickIdx].val)
if resultRoot != nil {
resultLast?.next = newNode
resultLast = newNode
} else {
resultRoot = newNode
resultLast = newNode
}
// advance
if let newTop = tops[pickIdx].next {
tops[pickIdx] = newTop
} else {
tops.remove(at: pickIdx)
}
}
return resultRoot
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment