Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Rotate a linked list to the right by k places.
Problem: Rotate a linked list to the right by k places.
class N:
def __init__(s, v, nx=None): s.v, s.nx = v, nx
def rotate(h, k):
n, t = 1, h
while t.nx: t = t.nx; n += 1
k %= n
if k == 0: return h
t.nx = h
for _ in range(n - k): t = t.nx
h = t.nx; t.nx = None
return h
h = None
for v in [5, 4, 3, 2, 1]: h = N(v, h)
h = rotate(h, 7); out = []
while h: out.append(h.v); h = h.nx
print(out)What is printed?- A. [3, 4, 5, 1, 2]
- B. [5, 1, 2, 3, 4]
- C. [4, 5, 1, 2, 3]
- D. [1, 2, 3, 4, 5]
Correct answer: C. [4, 5, 1, 2, 3]
Rotating by 7 on 5 nodes equals rotating by 7 mod 5 = 2: the last two nodes move to the front, giving [4, 5, 1, 2, 3]. Rotating LEFT by 2 would give [3, 4, 5, 1, 2].
More Coding Interview Problems questions
- Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part…
- List A has a nodes before it joins a shared tail of c nodes; list B has b nodes before the same tail, with a ≠ b. Pointer p walks A and…
- Problem: Move the coins of a binary tree so every node has exactly one coin; a move passes one coin along one edge. Count the minimum…
- Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree. python class T: def init(s, v): s.v, s.l, s.r = v, None…
- Problem: Return the (1-based) level of a binary tree with the largest sum of values (smallest level on ties). python class T: def init(s…
- Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if…