Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is.

Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is.
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 rev_k(h, k):
    n, cnt = h, 0
    while n and cnt < k:
        n = n.next; cnt += 1
    if cnt < k:
        return h
    prev, cur = rev_k(n, k), h
    for _ in range(k):
        cur.next, prev, cur = prev, cur, cur.next
    return prev
print(show(rev_k(build([1, 2, 3, 4, 5, 6, 7, 8]), 3)))
What is printed?
  1. A. [3, 2, 1, 6, 5, 4, 8, 7]
  2. B. [3, 2, 1, 6, 5, 4, 7, 8]
  3. C. [3, 2, 1, 4, 5, 6, 7, 8]
  4. D. [8, 7, 6, 5, 4, 3, 2, 1]

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

Check that k nodes exist, recursively process the rest, then reverse this group onto it. Groups [1,2,3] and [4,5,6] are reversed; [7,8] has fewer than 3 nodes and is left alone. O(n) time, O(n/k) recursion depth.

More Coding Interview Problems questions

Exams that ask this topic