LeetCode-in-Java

3839. Number of Prefix Connected Groups

Medium

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:

Example 1:

Input: words = [“apple”,”apply”,”banana”,”bandit”], k = 2

Output: 2

Explanation:

Words sharing the same first k = 2 letters are grouped together:

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:

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:

Thus, there are 2 connected groups, each containing at least two words.

Constraints:

Solution

public class Solution {
    public int prefixConnected(String[] words, int k) {
        java.util.HashMap<String, Integer> mpp = new java.util.HashMap<>();
        for (String word : words) {
            if (word.length() >= k) {
                String pref = word.substring(0, k);
                mpp.put(pref, mpp.getOrDefault(pref, 0) + 1);
            }
        }
        int cnt = 0;
        for (int y : mpp.values()) {
            if (y >= 2) {
                cnt++;
            }
        }
        return cnt;
    }
}