DSA Trie

Longest Common Prefix

Find the longest common prefix among all strings — vertical scan or trie walk.

Easy
Time O(S) Space O(1)
LeetCode
3 min read
strings

Problem#

Given an array of strings, return the longest common prefix shared by all of them. Return "" if there is none.

Examples#

  • ["flower","flow","flight"]"fl".
  • ["dog","racecar","car"]"".

Constraints#

  • 1 <= strs.length <= 200, 0 <= strs[i].length <= 200.

Hints#

Hint
Scan column by column; bail at the first mismatch or when a string ends.

Approach#

Vertical scan. At index i, compare every string’s i-th character against strs[0][i]. If any string is shorter than i or differs, return strs[0].substr(0, i).

Solution#

Longest Common Prefix
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
for (int i = 0; i < (int)strs[0].size(); ++i) {
char c = strs[0][i];
for (int j = 1; j < (int)strs.size(); ++j) {
if (i >= (int)strs[j].size() || strs[j][i] != c) return strs[0].substr(0, i);
}
}
return strs[0];
}
};

Editorial#

Vertical scan terminates as soon as one column disagrees, so total work is O(min_len * N) — much better than building a trie when the prefix is short. The trie alternative is conceptually cleaner but overkill for this size.

Complexity#

  • Time: O(S) where S is total characters in the prefix range.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.