KatInterview

869. Similar String Groups

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to partition a list of strings into groups based on a "similarity" relationship. All strings in the input list are guaranteed to be anagrams of each other and have the same length.

Solution

Similar String Groups in Python

class Solution:
    def numSimilarGroups(self, strs: list[str]) -> int:
        n = len(strs)
        if n <= 1:
            return n

        parent = list(range(n))
        num_groups = n

        # Find operation with path compression
        def find(i: int) -> int:
            if parent[i] == i:
                return i
            parent[i] = find(parent[i])
            return parent[i]

        # Union operation
        def union(i: int, j: int):
            nonlocal num_groups
            root_i = find(i)
            root_j = find(j)
            if root_i != root_j:
                parent[root_i] = root_j
                num_groups -= 1
        
        # Helper to check for similarity
        def is_similar(s1: str, s2: str) -> bool:
            diff_count = 0
            for k in range(len(s1)):
                if s1[k] != s2[k]:
                    diff_count += 1
            return diff_count == 0 or diff_count == 2

        # Compare all pairs of strings
        for i in range(n):
            for j in range(i + 1, n):
                if is_similar(strs[i], strs[j]):
                    union(i, j)
        
        return num_groups

Similar String Groups in Java

class Solution {
    // DSU structure as an inner class
    private class DSU {
        int[] parent;
        int count; // Number of disjoint sets

        DSU(int n) {
            parent = new int[n];
            count = n;
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }

        // Find operation with path compression
        public int find(int i) {
            if (parent[i] == i) {
                return i;
            }
            return parent[i] = find(parent[i]);
        }

        // Union operation
        public void union(int i, int j) {
            int rootI = find(i);
            int rootJ = find(j);
            if (rootI != rootJ) {
                parent[rootI] = rootJ;
                count--;
            }
        }

        public int getCount() {
            return count;
        }
    }

    public int numSimilarGroups(String[] strs) {
        int n = strs.length;
        if (n <= 1) {
            return n;
        }

        DSU dsu = new DSU(n);

        // Compare all pairs of strings
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (isSimilar(strs[i], strs[j])) {
                    dsu.union(i, j);
                }
            }
        }

        return dsu.getCount();
    }

    // Helper function to check if two strings are similar
    private boolean isSimilar(String a, String b) {
        int diffCount = 0;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) != b.charAt(i)) {
                diffCount++;
            }
        }
        // Similar if identical or differ by 2 characters (one swap)
        return diffCount == 0 || diffCount == 2;
    }
}

Similar String Groups in C++

class Solution {
public:
    vector<int> parent;
    int num_groups;

    // Find operation with path compression
    int find(int i) {
        if (parent[i] == i) {
            return i;
        }
        return parent[i] = find(parent[i]);
    }

    // Union operation
    void unite(int i, int j) {
        int root_i = find(i);
        int root_j = find(j);
        if (root_i != root_j) {
            parent[root_i] = root_j;
            num_groups--; // Decrement group count upon successful union
        }
    }

    // Helper function to check if two strings are similar
    bool isSimilar(const string& a, const string& b) {
        int diff_count = 0;
        for (int i = 0; i < a.length(); ++i) {
            if (a[i] != b[i]) {
                diff_count++;
            }
        }
        // Similar if identical or differ by 2 characters (one swap)
        return diff_count == 0 || diff_count == 2;
    }

    int numSimilarGroups(vector<string>& strs) {
        int n = strs.size();
        if (n <= 1) {
            return n;
        }

        // Initialize DSU
        parent.resize(n);
        for (int i = 0; i < n; ++i) {
            parent[i] = i;
        }
        num_groups = n;

        // Compare all pairs of strings
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (isSimilar(strs[i], strs[j])) {
                    unite(i, j);
                }
            }
        }

        return num_groups;
    }
};

Similar String Groups in TypeScript

function numSimilarGroups(strs: string[]): number {
    const n = strs.length;
    if (n <= 1) {
        return n;
    }

    const parent: number[] = Array.from({ length: n }, (_, i) => i);
    let numGroups = n;

    // Find operation with path compression
    function find(i: number): number {
        if (parent[i] === i) {
            return i;
        }
        parent[i] = find(parent[i]);
        return parent[i];
    }

    // Union operation
    function union(i: number, j: number): void {
        const rootI = find(i);
        const rootJ = find(j);
        if (rootI !== rootJ) {
            parent[rootI] = rootJ;
            numGroups--;
        }
    }

    // Helper function to check if two strings are similar
    function isSimilar(s1: string, s2: string): boolean {
        let diffCount = 0;
        for (let i = 0; i < s1.length; i++) {
            if (s1[i] !== s2[i]) {
                diffCount++;
            }
        }
        // Similar if identical or differ by 2 characters (one swap)
        return diffCount === 0 || diffCount === 2;
    }

    // Compare all pairs of strings
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            if (isSimilar(strs[i], strs[j])) {
                union(i, j);
            }
        }
    }

    return numGroups;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.