Article start
DSA Course: Interview Patterns and Problem Solving
Module 16: Trie & Advanced Data Structures

Longest Common Prefix: Single Branch Trie Pattern

Find the shared prefix by walking while there is one branch and no word ends.

May 29, 2026·25

Learning Outcome

After this lesson, you should be able to stop a prefix walk exactly when words branch or the shortest word ends.

Problem Statement

Given a list of strings, return the longest common prefix among them.

InputOutputWhy
strs = ["flower","flow","flight"]"fl"All strings start with fl, then flower and flow continue with o while flight continues with i.

Brute Force Approach

Try each possible prefix length and compare it with every string. This repeats character checks.

Optimized Approach

Insert the words into a trie, then walk from the root while the current node has exactly one child and is not a word end.

Exact Pseudocode

if strs is empty:
  return ""
insert every word into trie
node = root
prefix = ""
while node is not word end and node has exactly one child:
  move to the only child
  append that character
return prefix

Reference Code

class Solution:
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""

        root = {}
        for word in strs:
            node = root
            for ch in word:
                node = node.setdefault(ch, {})
            node["#"] = True

        node = root
        prefix = []
        while "#" not in node and len(node) == 1:
            ch = next(iter(node))
            prefix.append(ch)
            node = node[ch]
        return "".join(prefix)

Sample Dry Run

StepStateResult
Build pathsflower, flow, and flight share f then lsingle branch continues
At flnext children are o and ibranch found
Stopprefix collected is flreturn fl
Shortest word caseIf one word ends, stop thereavoid overrun

Complexity

MeasureValueReason
TimeO(total characters)Each inserted character is processed, then the common prefix is walked once.
SpaceO(total characters) for trie versionThe trie stores all inserted character nodes.

Edge Cases

  • If the input list is empty, return empty string.
  • If any string is empty, the answer is empty string.
  • Stop on word end even when there is still one child.

Interview Checklist

  • Detect branching by child count.
  • Detect shortest-word boundary with isWord.
  • Return the prefix collected before branching.

FAQs

Why stop when a word ends?

The common prefix cannot be longer than the shortest word.

Can this be solved without a trie?

Yes. Repeatedly shrinking the prefix is simpler and uses less extra memory, while trie teaches the prefix-branch idea.

What is the core pattern?

Single-branch prefix traversal.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.