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)?
- A. Interleave a copy after each original node, set copy.random = orig.random.next, then unweave the two lists
- B. Store original → copy in a hash map, then wire next and random pointers
- C. Recursively copy next and random with memoisation
- 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
- Problem: Simulate an LRU cache of capacity 3 (get returns −1 on a miss; a get or put marks the key most recently used). python from…
- Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs. python class T: def…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with…
- Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be…
- Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island. python g =…
- Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths. python from…