KatInterview

Three Classics: Spaced Characters, Merged Streams, Cloned Lists

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchheapgreedylinked-list

Last 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.