Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Add two numbers whose digits are stored in reverse order in linked lists.

Problem: Add two numbers whose digits are stored in reverse order in linked lists.
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 add(a, b):
    dummy = tail = Node(0); carry = 0
    while a or b or carry:
        s = carry + (a.v if a else 0) + (b.v if b else 0)
        carry, d = divmod(s, 10)
        tail.next = Node(d); tail = tail.next
        a = a.next if a else None
        b = b.next if b else None
    return dummy.next
print(show(add(build([9, 9, 9]), build([1]))))
What is printed?
  1. A. [0, 0, 0]
  2. B. [1, 0, 0, 0]
  3. C. [0, 0, 0, 1]
  4. D. [0, 0, 1]

Correct answer: C. [0, 0, 0, 1]

999 + 1 = 1000, stored in reverse as 0 → 0 → 0 → 1. The loop condition must include 'or carry', otherwise the final carry digit is lost ([0, 0, 0]). O(max(m, n)).

More Coding Interview Problems questions

Exams that ask this topic