1+ package com .thealgorithms .slidingwindow ;
2+
3+
4+ /**
5+ * Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
6+ * In other words, return true if one of s1's permutations is the substring of s2.
7+ *
8+ * Example:
9+ * Input: s1 = "ab", s2 = "eidbaooo"
10+ * Output: true
11+ * Explanation: s2 contains one permutation of s1 ("ba").
12+ *
13+ * Best Case Time Complexity: O(n)
14+ * Worst Case Time Complexity: O(m)
15+ * Space Complexity: O(1)
16+ *
17+ * @author m-saurabh01
18+ *
19+ */
20+
21+ class PermutationInString {
22+
23+ public boolean checkInclusion (String s1 , String s2 ) {
24+ // Get the length of s1 and s2
25+ int n = s1 .length ();
26+ int m = s2 .length ();
27+
28+ // Create frequency arrays for characters in s1 and the current window in s2
29+ int [] freq1 = new int [26 ]; // Frequency count for s1
30+ int [] freq2 = new int [26 ]; // Frequency count for current substring of s2
31+
32+ // Fill the frequency array for s1
33+ for (char c : s1 .toCharArray ()) {
34+ freq1 [c - 'a' ]++;
35+ }
36+
37+ // Slide the window of size n across s2
38+ for (int i = 0 ; i < m ; i ++) {
39+ // Add current character to the frequency array of the window
40+ freq2 [s2 .charAt (i ) - 'a' ]++;
41+
42+ // Check if the window size exceeds s1's length
43+ if (i >= n ) {
44+ // Remove the character that is no longer in the window
45+ freq2 [s2 .charAt (i - n ) - 'a' ]--;
46+ }
47+
48+ // If the frequency arrays match, return true
49+ if (i >= n - 1 ) { // Only check if we've processed enough characters
50+ boolean match = true ; // Assume they match
51+ for (int j = 0 ; j < 26 ; j ++) {
52+ if (freq1 [j ] != freq2 [j ]) { // If there's a mismatch
53+ match = false ; // Set match to false
54+ break ; // No need to check further
55+ }
56+ }
57+ if (match ) return true ; // If we found a match, return true
58+ }
59+ }
60+
61+ return false ; // No permutation of s1 found in s2
62+ }
63+ }
0 commit comments