Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

Rotate a linked list to the RIGHT by k places (k may exceed the length). What is printed?

Rotate a linked list to the RIGHT by k places (k may exceed the length). What is printed?
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
print(vals(rotate(build([1, 2, 3, 4, 5, 6]), 14)))
  1. A. [5, 6, 1, 3, 2, 4]
  2. B. [5, 6, 1, 2, 3, 4]
  3. C. [1, 2, 3, 4, 5, 6]
  4. D. [3, 4, 5, 6, 1, 2]

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

Only k mod n rotations matter. The list is made circular and cut after n − (k mod n) steps from the tail. Output: [5, 6, 1, 2, 3, 4].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic