KatInterview

Unlink From the Tail and Prune a Tree by Leaf Swap

Linked ListsModel answer
MediumModel answerLinked Listslinked-listtwo-pointersbinary-tree

Last 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 and O(1) extra space, where L is 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:

  1. Locate a node X whose value is key.
  2. Identify D, the deepest and rightmost node of the whole tree.
  3. Copy D.val into X.val.
  4. Detach D by setting its parent's matching child pointer to null.

Special cases:

  • If no node holds key, return the original root unchanged.
  • If the tree consists of a single node and it holds key, return null.

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.