Data Structures & AlgorithmsModerateTCS Digital · Infosys SP
Two numbers are stored as linked lists with digits in REVERSE order (units first). What does this addition print?
Two numbers are stored as linked lists with digits in REVERSE order (units first). What does this addition print?
def add(a, b):
d = t = N(0); c = 0
while a or b or c:
s = c + (a.v if a else 0) + (b.v if b else 0)
c, t.nx = s // 10, N(s % 10)
t = t.nx
a = a.nx if a else None; b = b.nx if b else None
return d.nx
print(vals(add(build([8, 9, 7, 9]), build([5, 7, 6]))))- A. [3, 7, 4, 0]
- B. [7, 3, 4, 0, 1]
- C. [3, 7, 4, 0, 1]
- D. [3, 4, 7, 0, 1]
Correct answer: C. [3, 7, 4, 0, 1]
Digits are added units-first with a carry; the loop also runs while a carry remains, which can add an extra most-significant digit at the end. Output: [3, 7, 4, 0, 1].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- How many contiguous subarrays of [5, 4, 4, 3, 2, 5, 2, 2] have a sum between 7 and 11 inclusive? (All values positive: count atMost(11) −…
- KMP failure function (lps[i] = length of the longest proper prefix of p[0..i] that is also a suffix). What is printed? python def lps(p)…
- Two numbers are stored as linked lists with digits in REVERSE order (units first). What does this addition print? python def add(a, b): d…
- A monotonic deque reports the maximum of every window of size 3 in [14, 5, −3, 14, 5, 14, −5, 16, 4]. What is the SUM of all reported…
- Delete duplicates from a SORTED linked list. Version A keeps one copy of each value; version B removes every value that appears more than…
- Which data structure gives O(1) worst-case time for inserting and deleting at BOTH ends and also O(1) access by index?