Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order.
Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order.
class N:
def __init__(s, v, nx=None): s.v, s.nx = v, nx
def odd_even(h):
if not h: return h
odd, even = h, h.nx; eh = even
while even and even.nx:
odd.nx = even.nx; odd = odd.nx
even.nx = odd.nx; even = even.nx
odd.nx = eh
return h
h = None
for v in reversed([2, 1, 3, 5, 6, 4, 7]): h = N(v, h)
h = odd_even(h); out = []
while h: out.append(h.v); h = h.nx
print(*out)What is printed?- A. 1 3 5 7 2 6 4
- B. 2 3 6 7 1 4 5
- C. 1 5 7 2 3 6 4
- D. 2 3 6 7 1 5 4
Correct answer: D. 2 3 6 7 1 5 4
Grouping is by position, not by value: positions 1, 3, 5, 7 hold 2, 3, 6, 7 and positions 2, 4, 6 hold 1, 5, 4. Grouping odd VALUES first would give '1 3 5 7 2 6 4', the trap.
More Coding Interview Problems questions
- Deep-copy a linked list whose nodes also have a random pointer. Which approach uses O(n) time and only O(1) extra space (besides the…
- Problem: Simulate an LRU cache of capacity 3 (get returns −1 on a miss; a get or put marks the key most recently used). python from…
- Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs. python class T: def…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with…
- Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be…
- Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island. python g =…