Chain All Words Into One String via Shared Letters
Trees & GraphsModel answerLast updated
Given a list of words, merge them into one string by joining where each word's last letter matches the next word's first letter, dropping the duplicate.
Chain All Words Into One String
You are given a list of n lowercase words. Your goal is to arrange them in some order and stitch them together into a single string using the following rule:
Two words can be joined back-to-back when the last character of the current string equals the first character of the next word. When you join them, the shared character appears only once.
You may use any ordering of the words. If you can find an ordering that uses every word exactly once, return the resulting merged string. If no such ordering exists, return "IMPOSSIBLE".
Example
Input: ["abc", "ctr", "rgn"]
Output: "abctrgn"
Explanation:
"abc"ends withc;"ctr"starts withc→ join to get"abctr"(drop the duplicatec)"abctr"ends withr;"rgn"starts withr→ join to get"abctrgn"(drop the duplicater)
What is expected
Describe and implement an algorithm that runs in near-linear time with respect to the total number of characters across all words.
Your answer should cover:
- The core insight that makes a linear-time solution possible (hint: think of words as something other than nodes in a path).
- The conditions under which a valid chain exists.
- The traversal algorithm you use and why you choose it over alternatives.
- Edge cases: self-loops (e.g.,
"aa"), repeated words, parallel edges, and disconnected components. - A working implementation with correct complexity.
Constraints
1 <= n <= 10^51 <= len(word) <= 50- All characters are lowercase English letters (
a–z)
Hints
Hint 1
Think of each word as a directed edge from its first character to its last character. There are only 26 possible nodes, no matter how many words there are.
Hint 2
A valid ordering of all words is exactly a walk that uses every edge once — that's an Eulerian path. Look up the degree conditions that determine whether one exists in a directed graph.
Hint 3
After verifying the degree conditions, run Hierholzer's algorithm iteratively (not recursively — n can reach 10^5 and blow the call stack). If the path you find covers fewer than n edges, some component was disconnected and the answer is IMPOSSIBLE.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Words as Edges, Not Nodes
The first instinct is to treat each word as a node and search for an ordering that visits every node once — a Hamiltonian path. That problem is NP-hard and completely unworkable at n = 10^5.
The right model flips the perspective: treat each letter as a node (26 total) and each word as a directed edge from its first character to its last. For example, "ctr" becomes the edge c → r.
A valid chain of all words is then a walk through this 26-node multigraph that uses every edge exactly once. That is precisely an Eulerian path, which can be found in linear time.
When Does an Eulerian Path Exist?
Define out[v] as the number of words starting with letter v and in[v] as the number ending with it.
Degree condition. One of two situations must hold:
- Circuit case: every node has
out[v] == in[v]. The path loops back to its start. - Open path case: exactly one node has
out − in = 1(the forced start), exactly one hasin − out = 1(the forced end), and all others are balanced.
Any node with |out − in| > 1 makes a valid path impossible.
Connectivity condition. All words must belong to a single connected component. Rather than running a separate BFS or union-find, you can detect disconnection for free: after Hierholzer's algorithm, check whether the path length equals n. If it falls short, some edges were unreachable.
Hierholzer's Algorithm (Iterative)
Hierholzer works by following edges greedily until stuck, then backfilling detours:
- Push
(start_node, sentinel)onto a stack. - While the stack is non-empty, look at the top:
- If the current node has an unused outgoing edge, consume it and push the destination.
- Otherwise, pop the node and record the edge that brought you here into the result list.
- Reverse the result to get the edge traversal order.
Use a per-node pointer (an integer index into each adjacency list) rather than actually removing edges. This keeps each step O(1) and the total time O(n).
Use the iterative version. A recursive DFS can reach depth n = 10^5, which overflows Python's default call stack. This is a detail interviewers notice.
Building the Output
Once you have the ordered list of word indices:
- Write the first word in full.
- For each subsequent word, append
word[1:]— everything except the first character, which is the shared one already present at the tail of the running string.
Build parts into a list and call "".join(parts) at the end. Repeated += on strings is O(L²) in the worst case.
Complexity
- Time: O(n + L) — O(n) to build the graph, O(n) for Hierholzer, O(L) to assemble the string (L = total characters).
- Space: O(n + L) — adjacency lists, stack, path buffer, output.
Edge Cases
Self-loops like "aa" become an a → a edge. They add 1 to both in[a] and out[a], so balance is preserved and Hierholzer handles them naturally. For a single-character word, word[1:] is the empty string, which is correct — the lone character is the shared one.
Parallel edges / duplicate words. Three copies of "ab" create three a → b edges. Words are tracked by index, so duplicates are distinct edges. Here out[a] = 3 and in[b] = 3, which fails the degree check — answer is IMPOSSIBLE.
Disconnected but degree-balanced. ["aa", "bb"] passes the degree check (both nodes are balanced) but the two edges are in separate components. Hierholzer starting at a yields a path of length 1, not 2 → IMPOSSIBLE. This is the case candidates most often miss when they skip the connectivity check.
No valid start chosen. In the open-path case the start node is forced: it must be the unique node with out − in = 1. Starting anywhere else produces a path that cannot be extended to cover all edges.
Python Implementation
from typing import List
def chain_words(words: List[str]) -> str:
n = len(words)
def char_idx(ch: str) -> int:
return ord(ch) - 97 # 'a' -> 0, 'z' -> 25
# Build directed multigraph: adj[u] holds indices of words starting at u
adj: list[list[int]] = [[] for _ in range(26)]
out_deg = [0] * 26
in_deg = [0] * 26
for i, word in enumerate(words):
u = char_idx(word[0])
v = char_idx(word[-1])
adj[u].append(i)
out_deg[u] += 1
in_deg[v] += 1
# Degree check and mandatory start-node selection
start = -1
forced_starts = forced_ends = 0
for v in range(26):
diff = out_deg[v] - in_deg[v]
if diff == 1:
forced_starts += 1
start = v
elif diff == -1:
forced_ends += 1
elif diff != 0:
return "IMPOSSIBLE"
valid_degree = (forced_starts == 0 and forced_ends == 0) or \
(forced_starts == 1 and forced_ends == 1)
if not valid_degree:
return "IMPOSSIBLE"
# Circuit case: start at any node that has an outgoing edge
if start == -1:
start = next((v for v in range(26) if out_deg[v] > 0), -1)
if start == -1:
return "IMPOSSIBLE" # no edges at all (shouldn't reach here given n >= 1)
# Iterative Hierholzer over word indices
ptr = [0] * 26 # next unused edge pointer per node
stack = [(start, -1)] # (current_node, word_index_used_to_arrive)
path: list[int] = []
while stack:
u, arriving_edge = stack[-1]
if ptr[u] < len(adj[u]):
word_idx = adj[u][ptr[u]]
ptr[u] += 1
v = char_idx(words[word_idx][-1])
stack.append((v, word_idx))
else:
stack.pop()
if arriving_edge != -1:
path.append(arriving_edge)
# Connectivity check: every word must appear in the path
if len(path) != n:
return "IMPOSSIBLE"
path.reverse()
# Assemble result, dropping the shared leading character for every word after the first
parts = [words[path[0]]]
for edge in path[1:]:
parts.append(words[edge][1:])
return "".join(parts)
Common Mistakes
- Modeling words as nodes instead of edges — leads to an NP-hard problem.
- Skipping the connectivity check and relying solely on degree conditions — fails on inputs like
["aa", "bb"]. - Using recursive DFS and hitting Python's recursion limit at large n.
- String concatenation in a loop instead of
"".join, causing O(L²) time. - Not enforcing the forced start node in the open-path case, producing a path that misses reachable edges.