Data Structures & AlgorithmsHardProduct company OA

Problem: Reorder a list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place: find the middle, reverse the second half, then interleave.

Problem: Reorder a list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place: find the middle, reverse the second half, then interleave.
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 reorder(head):
    slow = fast = head
    while fast.next and fast.next.next:
        slow = slow.next; fast = fast.next.next
    prev, cur = None, slow.next
    slow.next = None
    while cur:
        cur.next, prev, cur = prev, cur, cur.next
    a, b = head, prev
    while b:
        a.next, a = b, a.next
        b.next, b = a, b.next
    return head
print(show(reorder(build([1, 2, 3, 4, 5, 6, 7]))), show(reorder(build([1, 2, 3, 4]))))
What is printed?
  1. A. [1, 7, 2, 6, 3, 5, 4] [1, 3, 2, 4]
  2. B. [1, 7, 2, 6, 3, 5, 4] [1, 4, 2, 3]
  3. C. [7, 1, 6, 2, 5, 3, 4] [4, 1, 3, 2]
  4. D. [1, 2, 3, 7, 6, 5, 4] [1, 2, 4, 3]

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

slow stops at the end of the first half (node 4 for 7 nodes, node 2 for 4 nodes); the rest (5, 6, 7 / 3, 4) is cut and reversed to 7, 6, 5 / 4, 3, then merged alternately: 1 7 2 6 3 5 4 and 1 4 2 3. O(n) time and O(1) extra space; copying into an array would need O(n) space.

More Coding Interview Problems questions

Exams that ask this topic