Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Remove the k-th node from the end of a list in one pass.
Problem: Remove the k-th node from the end of a list in one pass.
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 remove_kth(h, k):
dummy = Node(0, h)
fast = slow = dummy
for _ in range(k + 1):
fast = fast.next
while fast:
fast, slow = fast.next, slow.next
slow.next = slow.next.next
return dummy.next
print(show(remove_kth(build([10, 20, 30, 40, 50]), 2)), show(remove_kth(build([7]), 1)))What is printed?- A. [10, 20, 40, 50] []
- B. [10, 20, 30, 50] [7]
- C. [10, 20, 30, 40] []
- D. [10, 20, 30, 50] []
Correct answer: D. [10, 20, 30, 50] []
fast starts k + 1 nodes ahead of slow (from a dummy), so when fast falls off the end, slow sits just before the node to delete. 2nd from the end of 10..50 is 40. The dummy head handles deleting the only node, which returns an empty list instead of crashing. O(n).
More Coding Interview Problems questions
- Problem: Merge two sorted linked lists into one sorted list. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt…
- Problem: Detect whether a linked list has a cycle and return the value where the cycle starts (None if acyclic). python class Node: def…
- Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is. python class Node: def…
- 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…