Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Merge two sorted linked lists into one sorted list.

Problem: Merge two sorted linked lists into one sorted list.
class Node:
    def __init__(self, v, nxt=None):
        self.v, self.next = v, nxt
def build(xs):
    head = None
    for x in reversed(xs):
        head = Node(x, head)
    return head
def show(h):
    out = []
    while h:
        out.append(h.v); h = h.next
    return out
def merge(a, b):
    tail = dummy = Node(0)
    while a and b:
        if a.v <= b.v:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next
print(show(merge(build([1, 4, 4, 9]), build([2, 4, 6]))))
What is printed?
  1. A. [1, 2, 4, 6, 9]
  2. B. [1, 2, 4, 4, 6, 9]
  3. C. [1, 2, 4, 4, 4, 6, 9]
  4. D. [1, 4, 4, 9, 2, 4, 6]

Correct answer: C. [1, 2, 4, 4, 4, 6, 9]

Standard splice with a dummy head; duplicates are kept, and whatever remains of one list is attached at the end with 'a or b'. O(m + n) time, O(1) extra space.

More Coding Interview Problems questions

Exams that ask this topic