Cover image for Interview Classic 150 Questions P14 Longest Common Prefix

Interview Classic 150 Questions P14 Longest Common Prefix


Timeline

Timeline

2025-11-09

init

Trie

Problem:

This problem can be solved by vertical scanning: look at the first character of each string, then the second, and so on.

The following is the Trie approach:
Note: isEnd is necessary because, for example, in the Trie for “flow” and “flower”, the children size of ‘w’ is also 1. If we don’t mark ‘flow’ as end, it will continue further.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <string>
#include <vector>
#include <unordered_map>

using std::string;
using std::vector;
using std::unordered_map;

struct Node {
unordered_map<char, Node *> children;
bool isEnd = false;
};

class Solution {
public:
string longestCommonPrefix(vector<string> &strs)
{
if (strs.empty())
return "";
Node *root = new Node();//A dummy node as root

// Insert all strings into the Trie
for (const string &s : strs) {
Node *p = root;
for (char c : s) {
if (!p->children.count(c)) {
p->children[c] = new Node();
}
p = p->children[c];
}
p->isEnd = true;
}

// Start from root and go down along the 'only branch'
string prefix;
Node *p = root;
while (p && p->children.size() == 1 && !p->isEnd) {
char next = p->children.begin()->first;
prefix.push_back(next);
p = p->children[next];
}

return prefix;
}
};