Data Structures & AlgorithmsHardAmazon · Microsoft OA

Deep-copy a linked list whose nodes also have a random pointer. Which approach uses O(n) time and only O(1) extra space (besides the output)?

  1. A. Interleave a copy after each original node, set copy.random = orig.random.next, then unweave the two lists
  2. B. Store original → copy in a hash map, then wire next and random pointers
  3. C. Recursively copy next and random with memoisation
  4. D. Copy the next chain first, then for each node find its random target by walking from the head

Correct answer: A. Interleave a copy after each original node, set copy.random = orig.random.next, then unweave the two lists

Interleaving lets each original's random target be reached in O(1) as orig.random.next, so no map is needed. The hash-map and memoised recursion approaches are O(n) time but O(n) extra space; walking from the head for every random pointer is O(n²).

More Coding Interview Problems questions

Exams that ask this topic