Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

839. Similar String Groups

Explanation

To solve this problem, we can use the concept of disjoint sets (Union-Find). We can iterate through all pairs of strings and if they are similar, we union their respective sets. After processing all pairs, the number of disjoint sets remaining will give us the number of groups.

For checking similarity between two strings, we can compare them character by character and keep track of the positions where the characters differ. If the number of differing positions is at most 2, the strings are similar.

  • Time complexity: O(n^2 * m) where n is the number of strings and m is the length of each string.
  • Space complexity: O(n)
class Solution {
    public int numSimilarGroups(String[] strs) {
        int n = strs.length;
        DSU dsu = new DSU(n);

        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (areSimilar(strs[i], strs[j])) {
                    dsu.union(i, j);
                }
            }
        }

        return dsu.getGroups();
    }

    private boolean areSimilar(String a, String b) {
        int diffCount = 0;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) != b.charAt(i)) {
                diffCount++;
                if (diffCount > 2) {
                    return false;
                }
            }
        }
        return true;
    }

    class DSU {
        int[] parent;

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

        public int find(int x) {
            if (parent[x] != x) {
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }

        public void union(int x, int y) {
            parent[find(x)] = find(y);
        }

        public int getGroups() {
            int groups = 0;
            for (int i = 0; i < parent.length; i++) {
                if (parent[i] == i) {
                    groups++;
                }
            }
            return groups;
        }
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.