ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
class N:
    def __init__(self, v, nxt=None):
        self.v, self.nxt = v, nxt
def mid(h):
    slow = fast = h
    while fast and fast.nxt:
        slow, fast = slow.nxt, fast.nxt.nxt
    return slow.v
print(mid(N(1, N(2, N(3, N(4, N(5)))))), mid(N(1, N(2, N(3, N(4))))))
  1. A. 3 2
  2. B. 2 3
  3. C. 4 3
  4. D. 3 3

Correct answer: D. 3 3

The slow pointer moves one step while the fast one moves two, so it stops at the middle node. For five nodes that is the third node, and for four nodes it is the third node as well, the second middle.

More Python Programming questions

Exams that ask this topic