KatInterview

Chain All Words Into One String via Shared Letters

Trees & GraphsModel answer
MediumModel answerTrees & Graphseulerian-pathgraphstrings

Last 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 with c; "ctr" starts with c → join to get "abctr" (drop the duplicate c)
  • "abctr" ends with r; "rgn" starts with r → join to get "abctrgn" (drop the duplicate r)

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:

  1. The core insight that makes a linear-time solution possible (hint: think of words as something other than nodes in a path).
  2. The conditions under which a valid chain exists.
  3. The traversal algorithm you use and why you choose it over alternatives.
  4. Edge cases: self-loops (e.g., "aa"), repeated words, parallel edges, and disconnected components.
  5. A working implementation with correct complexity.

Constraints

  • 1 <= n <= 10^5
  • 1 <= 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.