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.
| Input | Output | Why |
|---|---|---|
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
| Step | State | Result |
|---|---|---|
| Build paths | flower, flow, and flight share f then l | single branch continues |
| At fl | next children are o and i | branch found |
| Stop | prefix collected is fl | return fl |
| Shortest word case | If one word ends, stop there | avoid overrun |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(total characters) | Each inserted character is processed, then the common prefix is walked once. |
| Space | O(total characters) for trie version | The 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.
Tags
- dsa
- trie-advanced-ds
- single-branch trie traversal