ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
class N:
    def __init__(self, v):
        self.v = v
        self.nxt = None
def has_cycle(h):
    slow = fast = h
    steps = 0
    while fast and fast.nxt:
        slow = slow.nxt
        fast = fast.nxt.nxt
        steps += 1
        if slow is fast:
            return steps
    return -1
a, b, c = N(1), N(2), N(3)
a.nxt, b.nxt, c.nxt = b, c, b
print(has_cycle(a))
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: C. 2

Floyd's method moves a slow pointer one step and a fast pointer two steps. They meet after the second step, inside the cycle, so the function returns 2.

More Python Programming questions

Exams that ask this topic