[LeetCode] Number of Prefix Connected Groups

3839. Number of Prefix Connected Groups

You are given an array of strings words and an integer k.

Two words a and b at distinct indices are prefix-connected if a[0..k-1] == b[0..k-1].

A connected group is a set of words such that each pair of words is prefix-connected.

Return the number of connected groups that contain at least two words, formed from the given words.

Note:

  • Words with length less than k cannot join any group and are ignored.
  • Duplicate strings are treated as separate words.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int prefixConnected(vector<string>& words, int k) {
unordered_map<string,int> freq;
for(auto& w : words) {
if(w.length() < k) continue;
else freq[w.substr(0,k)]++;
}
int res = 0;
for(auto& [k,v] : freq) res += (v >= 2);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/number-of-prefix-connected-groups/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.