Java | Easy to understand
Intuition\n Describe your first thoughts on how to solve this problem. \n1. I tried to brute force the problem by finding all possible substrings and verfy them
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. I tried to brute force the problem by finding all possible substrings and verfy them, but it gets TLE.\n2. Then I was thinking if there is anything better than finding all possible substrings. The answer is yes. Since each character must occur exactly k times in a valid substring, the length of any valid substring must be a multiple of k. We only need to consider substrings of length k * uniqueCharacters, where uniqueCharacters ranges from 1 to the total number of unique characters in word.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int countCompleteSubstrings(String word, int k) {\n        int totalUniqueChars = (int) word.chars().distinct().count();\n        int count = 0;\n\n        for (int uniqueChars = 1; uniqueChars <= totalUniqueChars; uniqueChars++) {\n            int windowSize = uniqueChars * k;\n            if (windowSize > word.length()) {\n                break;\n            }\n\n            int[] charToCount = new int[26];\n            for (int i = 0; i < windowSize; i++) {\n                charToCount[word.charAt(i) - \'a\']++;\n            }\n\n            if (isEqualKTimes(charToCount, k) && areAdjacentCharsValid(word, 0, windowSize - 1)) {\n                count++;\n            }\n\n            for (int start = 1; start <= word.length() - windowSize; start++) {\n                charToCount[word.charAt(start - 1) - \'a\']--;\n                charToCount[word.charAt(start + windowSize - 1) - \'a\']++;\n\n                if (isEqualKTimes(charToCount, k) && areAdjacentCharsValid(word, start, start + windowSize - 1)) {\n                    count++;\n                }\n            }\n        }\n\n        return count;\n    }\n\n    private boolean isEqualKTimes(int[] charToCount, int k) {\n        for (int count : charToCount) {\n            if (count != 0 && count != k) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private boolean areAdjacentCharsValid(String word, int start, int end) {\n        for (int i = start; i < end; i++) {\n            if (Math.abs(word.charAt(i) - word.charAt(i + 1)) > 2) {\n                return false;\n            }\n        }\n        return true;\n    }\n}\n```
['Java']