Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Rotate a linked list to the right by k places.

Problem: Rotate a linked list to the right by k places.
class N:
    def __init__(s, v, nx=None): s.v, s.nx = v, nx
def rotate(h, k):
    n, t = 1, h
    while t.nx: t = t.nx; n += 1
    k %= n
    if k == 0: return h
    t.nx = h
    for _ in range(n - k): t = t.nx
    h = t.nx; t.nx = None
    return h
h = None
for v in [5, 4, 3, 2, 1]: h = N(v, h)
h = rotate(h, 7); out = []
while h: out.append(h.v); h = h.nx
print(out)
What is printed?
  1. A. [3, 4, 5, 1, 2]
  2. B. [5, 1, 2, 3, 4]
  3. C. [4, 5, 1, 2, 3]
  4. D. [1, 2, 3, 4, 5]

Correct answer: C. [4, 5, 1, 2, 3]

Rotating by 7 on 5 nodes equals rotating by 7 mod 5 = 2: the last two nodes move to the front, giving [4, 5, 1, 2, 3]. Rotating LEFT by 2 would give [3, 4, 5, 1, 2].

More Coding Interview Problems questions

Exams that ask this topic