Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is.
Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is.
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 rev_k(h, k):
n, cnt = h, 0
while n and cnt < k:
n = n.next; cnt += 1
if cnt < k:
return h
prev, cur = rev_k(n, k), h
for _ in range(k):
cur.next, prev, cur = prev, cur, cur.next
return prev
print(show(rev_k(build([1, 2, 3, 4, 5, 6, 7, 8]), 3)))What is printed?- A. [3, 2, 1, 6, 5, 4, 8, 7]
- B. [3, 2, 1, 6, 5, 4, 7, 8]
- C. [3, 2, 1, 4, 5, 6, 7, 8]
- D. [8, 7, 6, 5, 4, 3, 2, 1]
Correct answer: B. [3, 2, 1, 6, 5, 4, 7, 8]
Check that k nodes exist, recursively process the rest, then reverse this group onto it. Groups [1,2,3] and [4,5,6] are reversed; [7,8] has fewer than 3 nodes and is left alone. O(n) time, O(n/k) recursion depth.
More Coding Interview Problems questions
- Problem: Add two numbers whose digits are stored in reverse order in linked lists. python class Node: def init(self, v, nxt=None): self.v…
- Problem: An LRU cache of capacity c must support get(key) and put(key, value) in O(1) each, evicting the least recently used key. Which…
- Problem: The function below should check whether a singly linked list is a palindrome in O(1) extra space. python class Node: def…
- 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…