Unlink From the Tail and Prune a Tree by Leaf Swap
Linked ListsModel answerLast updated
Two pointer-manipulation tasks: remove the k-th node from the tail of a singly linked list, and delete a value from a general binary tree by overwriting it with the deepest-rightmost node's value.
Solve the two small tasks below. Assume the usual node classes: a list node has val and next, and a tree node has val, left and right.
Part 1: Drop the k-th node counting from the tail
You receive the head of a singly linked list and an integer k. Remove the node that sits k positions from the end (the last node is position 1) and return the head of the resulting list.
1 <= k <= length of the list.- Target
O(L)time andO(1)extra space, whereLis the number of nodes.
Part 2: Remove a value from a general binary tree
You receive the root of a binary tree that is not a search tree, plus an integer key. Delete exactly one node holding key and return the root, using this procedure:
- Locate a node
Xwhose value iskey. - Identify
D, the deepest and rightmost node of the whole tree. - Copy
D.valintoX.val. - Detach
Dby setting its parent's matching child pointer tonull.
Special cases:
- If no node holds
key, return the original root unchanged. - If the tree consists of a single node and it holds
key, returnnull.
Target O(N) time; O(N) extra space (for example a BFS queue) is acceptable, where N is the number of nodes.
What to deliver
Explain your approach for each part, give working code, state the complexity, and discuss the edge cases you would test.
Hints
Hint 1
Removing a node from a singly linked list requires access to the node before it. Think about a sentinel node placed in front of the head so removing the first node is not a special case.
Hint 2
For Part 1, keep two pointers separated by a fixed gap of k nodes. When the leading pointer reaches the last node, where is the trailing one?
Hint 3
For Part 2, a level-order traversal that enqueues left before right ends on exactly the deepest-rightmost node. Store each node's parent in the queue so you never need a second search.
Hint 4
When detaching the last visited node from its parent, compare by identity (is it the right child object?) rather than by value, since values can repeat.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Both parts reduce to one idea: to delete something safely you must hold the pointer that references it (the predecessor in a list, the parent in a tree), and you must handle the case where that referenced node is the head or root.
Part 1: Remove the k-th node from the tail
Approach
A two-pass solution (count the length, then walk to position L - k) is already O(L). The one-pass version uses a fixed gap between two pointers:
- Create a
dummynode pointing athead. This makes deleting the first real node identical to deleting any other. - Set
fastandslowtodummy. - Advance
fastexactlyktimes. - Advance both until
fast.nextisNone, sofastis on the last node. slowis now the predecessor of the target. Setslow.next = slow.next.next.- Return
dummy.next.
Why it works
Number the dummy as 0 and real nodes 1..L. After step 3, fast is at k and slow at 0. The gap k is preserved while moving, so when fast is at L, slow is at L - k, the predecessor of node L - k + 1, which is the k-th from the end. Because k <= L, fast never falls off the list during step 3, and slow.next always exists in step 5.
Complexity
Time O(L), space O(1).
Edge cases
- One node,
k = 1:slownever moves, sodummy.nextbecomesNone. k = L(remove the head): handled by the dummy; returndummy.next, not the oldhead.k = 1(remove the tail):slowends on the second-to-last node.
Part 2: Delete from a general binary tree
Approach
Because there is no ordering to preserve, we only need the tree to stay structurally valid. The deepest-rightmost node D is always a leaf (nothing lies below the deepest level), so cutting it off orphans nothing. Overwriting X.val with D.val then removes the key's value from the tree.
D is the last node dequeued in a BFS that pushes left before right. A single BFS can therefore:
- record the first node whose value equals
key(this isX), - track the last node dequeued (
D), - track
D's parent, by queuing(node, parent)pairs.
After the traversal: if X was never seen, return root; otherwise set X.val = D.val and null out the correct child pointer of D's parent.
Code
from collections import deque
def remove_from_tail(head, k):
dummy = ListNode(0, head)
fast = slow = dummy
for _ in range(k):
fast = fast.next
while fast.next is not None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
def delete_by_leaf_swap(root, key):
if root is None:
return None
if root.left is None and root.right is None:
return None if root.val == key else root
target = None
last = last_parent = None
q = deque([(root, None)])
while q:
node, parent = q.popleft()
if target is None and node.val == key:
target = node
last, last_parent = node, parent
if node.left:
q.append((node.left, node))
if node.right:
q.append((node.right, node))
if target is None:
return root
target.val = last.val
if last_parent.right is last:
last_parent.right = None
else:
last_parent.left = None
return root
Why it is correct
- BFS order is level by level, left to right, so the final node is on the deepest level and is its rightmost member.
- If
XisDitself, the copy is a no-op and the detach removes the target, which is right. - With more than one node,
Dis not the root, solast_parentexists. The single-node tree is handled up front. - Detaching uses
last_parent.right is last. If duplicates exist, a comparison by value could cut the wrong child.
Complexity
Time O(N), since each node is enqueued and dequeued once. Space O(W) for the queue, where W is the maximum width, and O(N) in the worst case.
Edge cases to test
- Empty tree: return
None. - Key absent: the tree is unchanged.
- Single node equal to
key: returnNone; single node not equal: return the root. - Duplicate keys: only the first match in BFS order is replaced.
- The target is the deepest-rightmost node itself.
Dis a left child because its parent has no right child.
Common mistakes
- Returning
headinstead ofdummy.nextin Part 1 after the head was deleted. - Looping with
while fastinstead ofwhile fast.next, which leavesslowone node too far and makes you delete the wrong node or crash. - Running three separate traversals in Part 2 (find X, find D, find D's parent). It is still
O(N)but more error-prone than one BFS with parents. - Treating Part 2 as BST deletion (successor or predecessor logic). The tree has no ordering, so that logic does not apply.
- Forgetting that the deepest-rightmost node may be the only child of its parent, hanging on the left.
Trade-offs
An alternative for Part 2 is a recursive DFS tracking depth, but it needs extra bookkeeping to break ties for "rightmost" at equal depth; BFS makes the definition fall out naturally. Deleting by leaf swap does not preserve any shape property, such as completeness, beyond removing one leaf, which is acceptable here because the task only requires a valid tree.