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:
k cannot join any group and are ignored.
Example 1:
Input: words = ["apple","apply","banana","bandit"], k = 2
Output: 2
Explanation:
Words sharing the same first k = 2 letters are grouped together:
words[0] = "apple" and words[1] = "apply" share prefix "ap".words[2] = "banana" and words[3] = "bandit" share prefix "ba".Thus, there are 2 connected groups, each containing at least two words.
Example 2:
Input: words = ["car","cat","cartoon"], k = 3
Output: 1
Explanation:
Words are evaluated for a prefix of length k = 3:
words[0] = "car" and words[2] = "cartoon" share prefix "car".words[1] = "cat" does not share a 3-length prefix with any other word.Thus, there is 1 connected group.
Example 3:
Input: words = ["bat","dog","dog","doggy","bat"], k = 3
Output: 2
Explanation:
Words are evaluated for a prefix of length k = 3:
words[0] = "bat" and words[4] = "bat" form a group.words[1] = "dog", words[2] = "dog" and words[3] = "doggy" share prefix "dog".Thus, there are 2 connected groups, each containing at least two words.
Constraints:
1 <= words.length <= 50001 <= words[i].length <= 1001 <= k <= 100words consist of lowercase English letters.Problem Overview: You receive an array of strings. Two strings belong to the same group if one string is a prefix of another. The task is to count how many distinct prefix-connected groups exist after considering all strings.
Approach 1: Pairwise Prefix Comparison (Brute Force) (Time: O(n^2 * L), Space: O(1))
The direct strategy compares every pair of strings and checks whether one is a prefix of the other. For each pair, iterate character by character until the prefix relationship either matches or fails. If a connection exists, mark them as belonging to the same group using simple visited/group markers. This works for small inputs but becomes slow because every pair of strings is examined. The repeated prefix checks make the runtime quadratic with respect to the number of strings.
Approach 2: Hash Table with Prefix Tracking (Optimal) (Time: O(n * L), Space: O(n))
Use a hash table to store strings that have already been processed. For each word, generate its prefixes from shortest to longest and check if any prefix already exists in the hash set. If a prefix is found, the current string belongs to that existing group. If none of its prefixes exist, this string starts a new group. Insert the full string into the hash table so later strings can connect through it. Since prefix generation costs O(L) per string and hash lookups are O(1) on average, the total complexity becomes O(n * L).
This method leverages the fact that prefix relationships can be detected incrementally while scanning the array once. Instead of comparing every pair, you only examine the prefixes of the current string and perform constant‑time membership checks in the hash structure. The idea is closely related to prefix detection used in string problems and frequency tracking from counting techniques.
Recommended for interviews: Interviewers expect the hash table approach. The brute force solution demonstrates that you understand the prefix relationship definition, but the optimized method shows you can eliminate redundant comparisons using hashing. Recognizing that previously seen prefixes can represent entire groups is the key insight.
We use a hash table cnt to count the number of occurrences of the prefix composed of the first k characters of each string with length greater than or equal to k. Finally, we count the number of keys in cnt with values greater than 1, which is the number of connected groups.
The time complexity is O(n times k), and the space complexity is O(n), where n is the length of words.
Python
Java
C++
Go
TypeScript
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Pairwise Prefix Comparison | O(n^2 * L) | O(1) | Useful for understanding the prefix relationship or when input size is very small |
| Hash Table with Prefix Tracking | O(n * L) | O(n) | General case and interview scenarios where efficient prefix detection is required |
LeetCode 3839: Number of Prefix Connected Groups | Biweekly 176 • CodingHelp • 161 views views
Watch 4 more video solutions →Practice Number of Prefix Connected Groups with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor