Three Classics: Spaced Characters, Merged Streams, Cloned Lists
Heaps, Sorting & SearchModel answerLast updated
Solve three linked tasks: rearrange a string so no neighbors match, merge k sorted linked lists, and deep-copy a linked list whose nodes carry an extra arbitrary pointer.
Answer the three tasks below. For each, explain your approach, state its complexity, and write working code.
Task 1: Rearrange with no equal neighbors
Given a string s of lowercase letters, rearrange its characters so that no two adjacent characters are the same. Return any valid arrangement, or the empty string "" if none exists.
Examples:
"aab"->"aba""aaab"->""
Task 2: Merge k sorted linked lists
You get an array of k singly linked lists, each sorted in ascending order. Splice all their nodes into one sorted linked list and return its head. The array may be empty, and individual lists may be empty.
Task 3: Deep copy of a list with an extra pointer
Each node of a singly linked list has a val, a next pointer, and a random pointer. random may point to any node in the list (including itself) or be None. Build a deep copy: every new node must be a fresh object, and the next and random pointers in the copy must reference only copied nodes, never originals. Return the head of the copy.
Expected from you
- Say when Task 1 is impossible, and justify the condition.
- Say how you avoid comparing node objects in Task 2, and compare at least two approaches.
- Give a hash-map solution for Task 3, then discuss whether extra space can be reduced to constant.
- List the edge cases you would test for each task.
Hints
Hint 1
Task 1: let n be the length and m the highest letter count. No two copies of one letter can touch, so think about how many slots a single letter can occupy without adjacency, then think about filling positions 0, 2, 4, ... first.
Hint 2
Task 2: only the current front node of each list can be the next smallest output node, so you need a structure that returns the minimum of at most k candidates quickly. Push a tiebreaker alongside the value so equal values never force a comparison between nodes.
Hint 3
Task 3: the hard part is finding the copy of a node's random target. A map from original to copy solves it directly. To avoid the map, temporarily place each copy right after its original, so the copy of any node X is simply X.next.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Task 1: Rearrange with no equal neighbors
Feasibility. Let n = len(s) and m be the highest letter frequency. A letter with no two copies adjacent can occupy at most ceil(n/2) = (n + 1) // 2 positions. So if m > (n + 1) // 2, the answer is "". Otherwise an arrangement always exists.
Construction (linear time).
- Count the letters.
- Order them so the most frequent letter comes first. The rest can follow in any order, but each letter's copies must stay contiguous in this order.
- Write the letters one by one into positions
0, 2, 4, .... After passing the last even index, continue at1, 3, 5, ....
Why it works. The top letter takes only even slots, which are never adjacent. Any other letter either stays within one parity, so it is safe, or it wraps. A wrapping letter c has fewer copies than the top letter can leave room for, because it starts after the top letter's block, so its even copies sit at indices of at least 2m while its odd copies end below 2*count(c). Since count(c) <= m, the two groups cannot touch.
Alternative. A max-heap greedy repeatedly takes the two most frequent remaining letters and appends both, costing O(n log σ) for alphabet size σ. It is easier to reason about but slower than the slot fill.
from collections import Counter
def reorganize(s: str) -> str:
n = len(s)
cnt = Counter(s)
top = max(cnt, key=cnt.get)
if cnt[top] > (n + 1) // 2:
return ""
out = [""] * n
pos = 0
for ch in [top] + [c for c in cnt if c != top]:
for _ in range(cnt[ch]):
if pos >= n:
pos = 1
out[pos] = ch
pos += 2
return "".join(out)
Complexity: O(n) time, O(σ) extra space plus the output.
Edge cases: a single character; all letters distinct; the top count exactly equal to (n+1)//2 with odd n (e.g. "aba").
Task 2: Merge k sorted linked lists
Heap approach. Keep a min-heap with the current front node of every non-empty list. Repeatedly pop the smallest, attach it to the output tail, and push its successor if it has one. The smallest remaining node overall must be the front of some list, because each list is sorted, so the heap minimum is always correct.
Python cannot order ListNode objects, so push tuples (val, list_index, node). The index is unique per list, so ties on val never reach the node comparison. Without it, equal values raise a TypeError.
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_k(lists):
heap = [(n.val, i, n) for i, n in enumerate(lists) if n]
heapq.heapify(heap)
dummy = tail = ListNode()
while heap:
_, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.next
Complexity. With N total nodes, each node is pushed and popped once on a heap of size at most k, giving O(N log k) time and O(k) space. Nodes are relinked rather than copied.
Alternatives.
- Divide and conquer: merge lists pairwise in rounds. It is also
O(N log k)and needsO(1)extra space when written iteratively. - Merging into one accumulating list is
O(N k)in the worst case, because early nodes are traversed again in each merge. This is the common naive mistake.
Edge cases: an empty array, all lists empty, one list, duplicate values across lists, and lists of very different lengths.
Task 3: Deep copy with random pointers
Hash map version. Pass 1 creates a copy of every node and stores old -> new. Pass 2 sets new[old].next = new[old.next] and new[old].random = new[old.random], treating None as mapping to None. This is O(n) time and O(n) space, and it is perfectly acceptable.
Constant extra space version. Interleave the copies with the originals:
- Weave: for each original
X, insert its copyX'right after it, givingA -> A' -> B -> B' -> .... - Wire randoms: for each original
Xwith a random target, setX'.random = X.random.next. After weaving, the node after any original is its copy. - Unweave: restore each original's
nextand extract the copies into a separate list.
class Node:
def __init__(self, val, next=None, random=None):
self.val = val
self.next = next
self.random = random
def copy_list(head):
if not head:
return None
cur = head
while cur:
cur.next = Node(cur.val, cur.next)
cur = cur.next.next
cur = head
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
new_head = head.next
cur = head
while cur:
dup = cur.next
cur.next = dup.next
dup.next = dup.next.next if dup.next else None
cur = cur.next
return new_head
Complexity: O(n) time, O(1) extra space beyond the copy itself.
Common mistakes:
- Setting the copy's
randomto the original's target, which shares nodes instead of copying. - Unweaving incorrectly, leaving the original list damaged.
- Running the random-wiring pass after partially unweaving.
Edge cases: an empty list, random equal to None, random pointing to the node itself, many nodes sharing one target, and a single-node list.
Summary of trade-offs
| Task | Preferred method | Time | Extra space |
|---|---|---|---|
| Rearrange | Slot fill by parity | O(n) | O(σ) |
| Merge k lists | Min-heap or pairwise merge | O(N log k) | O(k) or O(1) |
| Deep copy | Weave and unweave | O(n) | O(1) |
State the invariant before each piece of code, since a wrong invariant is the most frequent cause of bugs here.