From f97c6e26b29e86639db6fdd9dbbebecd149bef9f Mon Sep 17 00:00:00 2001 From: EswarReddy15 <154427709+EswarReddy15@users.noreply.github.com> Date: Fri, 31 Oct 2025 19:11:28 +0530 Subject: [PATCH] Implement checkInclusion method for string permutations --- Permutations of a given string | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Permutations of a given string diff --git a/Permutations of a given string b/Permutations of a given string new file mode 100644 index 000000000..52a043d48 --- /dev/null +++ b/Permutations of a given string @@ -0,0 +1,46 @@ +public class Solution { + public boolean checkInclusion(String s1, String s2) { + if (s1.length() > s2.length()) { + return false; + } + + int[] s1Count = new int[26]; + int[] s2Count = new int[26]; + for (int i = 0; i < s1.length(); i++) { + s1Count[s1.charAt(i) - 'a']++; + s2Count[s2.charAt(i) - 'a']++; + } + + int matches = 0; + for (int i = 0; i < 26; i++) { + if (s1Count[i] == s2Count[i]) { + matches++; + } + } + + int l = 0; + for (int r = s1.length(); r < s2.length(); r++) { + if (matches == 26) { + return true; + } + + int index = s2.charAt(r) - 'a'; + s2Count[index]++; + if (s1Count[index] == s2Count[index]) { + matches++; + } else if (s1Count[index] + 1 == s2Count[index]) { + matches--; + } + + index = s2.charAt(l) - 'a'; + s2Count[index]--; + if (s1Count[index] == s2Count[index]) { + matches++; + } else if (s1Count[index] - 1 == s2Count[index]) { + matches--; + } + l++; + } + return matches == 26; + } +}