Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Rotate a linked list to the right by k places (k may exceed the length).

Problem: Rotate a linked list to the right by k places (k may exceed the length).
class Node:
    def __init__(self, v, nxt=None): self.v, self.next = v, nxt
def build(xs):
    head = None
    for x in reversed(xs): head = Node(x, head)
    return head
def show(h):
    out = []
    while h: out.append(h.v); h = h.next
    return out
def rotate(head, k):
    if not head: return head
    n, tail = 1, head
    while tail.next: tail = tail.next; n += 1
    k %= n
    if k == 0: return head
    new_tail = head
    for _ in range(n - k - 1): new_tail = new_tail.next
    new_head = new_tail.next
    new_tail.next = None; tail.next = head
    return new_head
print(show(rotate(build([1, 2, 3, 4, 5]), 7)), show(rotate(build([8, 9]), 4)))
What is printed?
  1. A. [5, 1, 2, 3, 4] [8, 9]
  2. B. [4, 5, 1, 2, 3] [8, 9]
  3. C. [3, 4, 5, 1, 2] [8, 9]
  4. D. [4, 5, 1, 2, 3] [9, 8]

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

Measure the length n, reduce k mod n (7 mod 5 = 2, 4 mod 2 = 0), cut after node n − k and attach the old tail to the old head. Rotating right by 2 moves the last two nodes (4, 5) to the front. Without k %= n the loop would run a negative or huge number of steps; rotating by a multiple of n is the identity. O(n).

More Coding Interview Problems questions

Exams that ask this topic