Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: The function below should check whether a singly linked list is a palindrome in O(1) extra space.

Problem: The function below should check whether a singly linked list is a palindrome in O(1) extra space.
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 is_pal(h):
    slow = fast = h
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    prev = None
    while slow:
        slow.next, prev, slow = prev, slow, slow.next
    while prev:
        if prev.v != h.v: return False
        prev, h = prev.next, h.next
    return True
print(is_pal(build([1, 2, 3, 2, 1])), is_pal(build([1, 2, 2, 1])), is_pal(build([1, 2])))
What is printed?
  1. A. True True False
  2. B. True False False
  3. C. True True True
  4. D. False True False

Correct answer: A. True True False

Find the middle, reverse the second half, then compare it with the first half. For odd length the middle node ends up in both halves, which is harmless. Each phase is O(n) with O(1) extra memory (a production version would re-reverse to restore the list).

More Coding Interview Problems questions

Exams that ask this topic