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?- A. True True False
- B. True False False
- C. True True True
- 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
- Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a…
- Problem: Print the level-order traversal of a tree, one list per level. Trees are built by build(xs): a level-order list where index i has…
- Problem: Return the right-side view of a tree (the last node of each level). Trees are built by build(xs): a level-order list where index…
- Problem: Check whether a binary tree is a valid BST. The candidate solution compares each node only with its children. Trees are built by…
- Problem: Find the lowest common ancestor of two keys in a BST. Trees are built by build(xs): a level-order list where index i has children…
- Problem: Find the k-th smallest key in a BST. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2…