Longest Common Prefix Trie DSA Solution - Study Chapter | QuizMaker

Longest Common Prefix explained with repeated prefix comparison, trie branch walk, dry run, edge cases, complexity, and Python, C++, Java code.

Read
12m
Type
Chapter
Access
Free

Course

DSA Course: Interview Patterns and Problem Solving

Topic

Module 16: Trie & Advanced Data Structures

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)
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";

        string prefix = strs[0];
        for (int i = 1; i < strs.size(); i++) {
            int j = 0;
            while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j]) {
                j++;
            }
            prefix = prefix.substr(0, j);
            if (prefix.empty()) break;
        }
        return prefix;
    }
};
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";

        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            int j = 0;
            while (j < prefix.length() && j < strs[i].length()
                    && prefix.charAt(j) == strs[i].charAt(j)) {
                j++;
            }
            prefix = prefix.substring(0, j);
            if (prefix.isEmpty()) break;
        }
        return 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

Interview Checklist

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.

Tags

Open on QuizMaker