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?- A. [0, 0, 0]
- B. [1, 0, 0, 0]
- C. [0, 0, 0, 1]
- 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
- Problem: An LRU cache of capacity c must support get(key) and put(key, value) in O(1) each, evicting the least recently used key. Which…
- Problem: The function below should check whether a singly linked list is a palindrome in O(1) extra space. python class Node: def…
- Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a…
- Problem: Print the level-order traversal of a tree, one list per level. Trees are built by build(xs): a level-order list where index i has…
- Problem: Return the right-side view of a tree (the last node of each level). Trees are built by build(xs): a level-order list where index…
- Problem: Check whether a binary tree is a valid BST. The candidate solution compares each node only with its children. Trees are built by…