|
| 1 | +/** |
| 2 | + * @name The-Sliding-Window Algorithm is primarily used for the problems dealing with linear data structures like Arrays, Lists, Strings etc. |
| 3 | + * These problems can easily be solved using Brute Force techniques which result in quadratic or exponential time complexity. |
| 4 | + * Sliding window technique reduces the required time to linear O(n). |
| 5 | + * @see [The-Sliding-Window](https://www.geeksforgeeks.org/window-sliding-technique/) |
| 6 | + */ |
| 7 | +/** |
| 8 | + * @function PermutationinString |
| 9 | + * @description Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. |
| 10 | + * @param {String} s1 - The input string |
| 11 | + * @param {String} s2 - The input string |
| 12 | + * @return {boolean} - Returns true if s2 contains a permutation of s1, or false otherwise. |
| 13 | + */ |
| 14 | + |
| 15 | +export function PermutationinString (s1, s2) { |
| 16 | + if (s1.length > s2.length) return false |
| 17 | + let start = 0 |
| 18 | + let end = s1.length - 1 |
| 19 | + const s1Set = SetHash() |
| 20 | + const s2Set = SetHash() |
| 21 | + for (let i = 0; i < s1.length; i++) { |
| 22 | + s1Set[s1[i]]++ |
| 23 | + s2Set[s2[i]]++ |
| 24 | + } |
| 25 | + if (equals(s1Set, s2Set)) return true |
| 26 | + while (end < s2.length - 1) { |
| 27 | + if (equals(s1Set, s2Set)) return true |
| 28 | + end++ |
| 29 | + console.log(s2[start], s2[end], equals(s1Set, s2Set)) |
| 30 | + const c1 = s2[start] |
| 31 | + const c2 = s2[end] |
| 32 | + if (s2Set[c1] > 0) s2Set[c1]-- |
| 33 | + s2Set[c2]++ |
| 34 | + start++ |
| 35 | + if (equals(s1Set, s2Set)) return true |
| 36 | + } |
| 37 | + return false |
| 38 | +} |
| 39 | +function equals (a, b) { |
| 40 | + return JSON.stringify(a) === JSON.stringify(b) |
| 41 | +} |
| 42 | + |
| 43 | +function SetHash () { |
| 44 | + const set = new Set() |
| 45 | + const alphabets = 'abcdefghijklmnopqrstuvwxyz' |
| 46 | + for (let i = 0; i < alphabets.length; i++) { |
| 47 | + set[alphabets[i]] = 0 |
| 48 | + } |
| 49 | + return set |
| 50 | +} |
| 51 | + |
| 52 | +// Example 1: |
| 53 | +// Input: s1 = "ab", s2 = "eidbaooo" |
| 54 | +// Output: true |
| 55 | +// Explanation: s2 contains one permutation of s1 ("ba"). |
| 56 | + |
| 57 | +// Example 2: |
| 58 | +// Input: s1 = "ab", s2 = "eidboaoo" |
| 59 | +// Output: false |
0 commit comments