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?- A. [1, 7, 2, 6, 3, 5, 4] [1, 3, 2, 4]
- B. [1, 7, 2, 6, 3, 5, 4] [1, 4, 2, 3]
- C. [7, 1, 6, 2, 5, 3, 4] [4, 1, 3, 2]
- 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
- Problem: Find the area of the largest all-'1' rectangle in a binary grid by treating each row as the base of a histogram and running the…
- Problem: Does a price series contain a '132' pattern – indices i < j < k with a[i] < a[k] < a[j]? Scan from the right with a decreasing…
- Problem: Delete repeated letters so each letter appears once, and among all such results return the lexicographically smallest (a…
- Problem: A game board has scores a[0..n−1]; from cell i you may jump forward 1..k cells. Starting at 0 and ending at n − 1, maximise the…
- Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has…
- Problem: People stand in a line facing right with distinct heights. Person i can see person j > i if everyone strictly between them is…