LeetCode #3839 — MEDIUM

Number of Prefix Connected Groups

Move from brute-force thinking to an efficient approach using core interview patterns strategy.

Solve on LeetCode
The Problem

Problem Statement

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.

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 <= 5000
  • 1 <= words[i].length <= 100
  • 1 <= k <= 100
  • All strings in words consist of lowercase English letters.

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: General problem-solving

Example 1

["apple","apply","banana","bandit"]
2

Example 2

["car","cat","cartoon"]
3

Example 3

["bat","dog","dog","doggy","bat"]
3
Step 02

Core Insight

What unlocks the optimal approach

  • Filter out words with length < <code>k</code>; they can never participate in any valid group.
  • Two words are connected exactly when their first <code>k</code> characters are identical; this reduces the problem to grouping by prefix.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3839: Number of Prefix Connected Groups
class Solution {
    public int prefixConnected(String[] words, int k) {
        Map<String, Integer> cnt = new HashMap<>();
        for (var w : words) {
            if (w.length() >= k) {
                cnt.merge(w.substring(0, k), 1, Integer::sum);
            }
        }
        int ans = 0;
        for (var v : cnt.values()) {
            if (v > 1) {
                ++ans;
            }
        }
        return ans;
    }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × k)
Space
O(n)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.

OPTIMIZED
O(n) time
O(1) space

Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.

Shortcut: If you are using nested loops on an array, there is almost always an O(n) solution. Look for the right auxiliary state.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.