Magicsheet logo

Longest String Chain

Medium
56.8%
Updated 6/1/2025

Longest String Chain

What is this problem about?

The Longest String Chain problem gives you an array of words. A word A is a predecessor of word B if you can insert exactly one lowercase English letter anywhere into A to make it exactly equal to B (e.g., "abc" -> "abac"). A "word chain" is a sequence of words where each is a predecessor of the next. Your goal is to find the maximum possible length of a word chain chosen from the given array.

Why is this asked in interviews?

This is a highly popular medium-level dynamic programming question. Interviewers love it because it tests multiple skills simultaneously: custom sorting, hash map manipulation, and string processing. It evaluates whether a candidate can break a string down into its sub-components and connect states dynamically, mimicking real-world logic used in spell-checkers and graph-based search algorithms.

Algorithmic pattern used

This problem leverages Sorting and Dynamic Programming with a Hash Map. First, sort the array of words by their length (shortest to longest) because a chain must build upwards. Then, create a Hash Map to store dp[word] = longest_chain_length. For each word, generate all possible predecessors by removing one character at a time. If a predecessor exists in the map, the current word's chain length is dp[predecessor] + 1.

Example explanation

Words: ["a", "b", "ba", "bca", "bda", "bdca"]

  1. Sort by length: ["a", "b", "ba", "bca", "bda", "bdca"].
  2. Map initialized.
  • "a": Predecessor "" (not in map). Map: {"a": 1}.
  • "b": Predecessor "". Map: {"a": 1, "b": 1}.
  • "ba": Predecessors "a" and "b". Both in map with length 1. So "ba" gets 1+1=21 + 1 = 2. Map: {..., "ba": 2}.
  • "bda": Predecessors "da", "ba", "bd". "ba" is in map with length 2! "bda" gets 2+1=32 + 1 = 3. Map {..., "bda": 3}.
  • "bdca": Predecessors include "bda". "bda" is 3. "bdca" gets 3+1=43 + 1 = 4. The max chain length is 4 ("b" -> "ba" -> "bda" -> "bdca").

Common mistakes candidates make

A major mistake is trying to build words up by adding characters and checking if the longer word exists. Because there are 26 possible letters to insert at any position, this creates 26×L26 \times L checks per word. Removing a character only takes LL checks! Always prefer deletion over insertion when backtracking string relationships to save computational time.

Interview preparation tip

To master the Longest String Chain coding problem, practice generating all single-character deletions of a string efficiently using string slicing (e.g., word[:i] + word[i+1:]). This technique is a massive time-saver in Python and Java. Also, remember that sorting by length is the critical first step; without it, your DP map will look for previous states that haven't been computed yet.

Similar Questions