Sliding Window Approach in Java
Approach\n1. Use a hashmap to count characters in word2.\n2. Use a sliding window approach with two pointers to find valid substrings in word1.\n3. Count how ma
# Approach\n1. Use a hashmap to count characters in `word2`.\n2. Use a sliding window approach with two pointers to find valid substrings in `word1`.\n3. Count how many valid substrings can be formed by adjusting the window size based on character matches.\n\n# Complexity\n- Time complexity: $$O(n)$$ (where $$n$$ is the length of `word1`)\n- Space complexity: $$O(m)$$ (where $$m$$ is the length of `word2`, for storing character counts)\n\n# Code\n```java\nclass Solution {\n    public long validSubstringCount(String word1, String word2) {\n        int n = word1.length();\n        int m = word2.length();\n        if (m > n) return 0;\n\n        HashMap<Character, Integer> count2 = new HashMap<>();\n        HashMap<Character, Integer> count1 = new HashMap<>();\n\n        for (char c : word2.toCharArray()) {\n            count2.put(c, count2.getOrDefault(c, 0) + 1);\n        }\n\n        long result = 0;\n        int required = count2.size();\n        int formed = 0;\n        int left = 0;\n\n        for (int right = 0; right < n; ++right) {\n            char c = word1.charAt(right);\n            count1.put(c, count1.getOrDefault(c, 0) + 1);\n\n            if (count2.containsKey(c) && count1.get(c).intValue() == count2.get(c).intValue()) {\n                formed++;\n            }\n\n            while (formed == required) {\n                result += (n - right);\n                char leftChar = word1.charAt(left);\n                count1.put(leftChar, count1.get(leftChar) - 1);\n                \n                if (count2.containsKey(leftChar) && count1.get(leftChar) < count2.get(leftChar)) {\n                    formed--;\n                }\n                left++;\n            }\n        }\n\n        return result;\n    }\n}\n```\n# Upvote if you found this helpful! \uD83D\uDE0A
['Java']