Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass.
Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass.
class N:
def __init__(s, v, nx=None): s.v, s.nx = v, nx
def rev_between(head, m, n):
dummy = N(0, head); pre = dummy
for _ in range(m - 1): pre = pre.nx
cur = pre.nx
for _ in range(n - m):
t = cur.nx
cur.nx = t.nx; t.nx = pre.nx; pre.nx = t
return dummy.nx
h = None
for v in range(7, 0, -1): h = N(v, h)
h = rev_between(h, 2, 5); out = []
while h: out.append(h.v); h = h.nx
print(*out)What is printed?- A. 1 5 4 3 2 7 6
- B. 1 5 4 3 2 6 7
- C. 1 2 5 4 3 6 7
- D. 5 4 3 2 1 6 7
Correct answer: B. 1 5 4 3 2 6 7
The head-insertion loop moves each next node to just after pre, so positions 2–5 become 5 4 3 2 while 1, 6 and 7 stay in place. A dummy node makes m = 1 work without a special case.
More Coding Interview Problems questions
- Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order. python class N: def…
- 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…