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))- A. 1
- B. 3
- C. 2
- 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
- What is printed? python print(hash(-1), hash(-2), hash(-1) == -2, hash(1) == hash(1.0))
- What is printed? python print(232, (23)2, -22, (-2)2, 2-12)
- What is printed? python print(float(254) + 1 == 254, 254 + 1 == float(254), 1e16 + 2 == 1e16 + 1)
- What is printed? python print(int('١٢٣'), int('0' 2 + '5'), int('5' + '0' 2), int(' t7n'))
- What is printed? python print(bin(-8 & 0xFF), (-8) >> 1, (-8) // 2, (-9) // 2, -9 >> 1)
- What is printed? python print(x := 7, x 2, [y := 3, y + 1])