Two pointers, always take the smaller head
Both lists are already sorted. At each step emit the smaller current head and advance that list.
Same merge as in merge-sort. Because each head is the smallest remaining value on its side, the global next value is min(l1[i], l2[j]).
Algorithm
- Walk
ionl1andjonl2. - While both remain, append the smaller value and advance that pointer.
- Append whatever is left on the other list.
- Time
- O(n + m)
- Space
- O(n + m)
class Solution: def mergeTwoLists(self, l1: list[int], l2: list[int]) -> list[int]: out: list[int] = [] i = j = 0 while i < len(l1) and j < len(l2): if l1[i] <= l2[j]: out.append(l1[i]) i += 1 else: out.append(l2[j]) j += 1 out.extend(l1[i:]) out.extend(l2[j:]) return out