Given two strings X and Y containing lower-case alphabets, the task is to check whether any permutation of string X exists in Y as its substring.
Input: X = “skege”, Y = “geeksforgeeks”
“geeks” is a permutation of X which
appears as a substring in Y.
Input: X = “aabb”, Y = “bbbbbbb”
Approach: This problem can be solved using the two pointer technique.
- Compute the frequency count of every character of string X and store it in an array say cnt_X.
- Now for substring Y[i…(i+X.length()-1)], the same frequency array can be generated say cnt.
- Using the array from step 2, the frequency count for the next window can be calculated in O(1) time by decrementing cnt[Y[i] – ‘a’] by 1 and incrementing cnt[Y[i + X.length()] – ‘a’] by 1.
- Compare cnt and cnt_X for every window. If both of them are equal then a match has been found.
Below is the implementation of the above approach:
Time Complexity: O(xLen + yLen) where xLen and yLen are the lengths of the strings X and Y respectively.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the number of elements X such that X + K also exists in the array
- Check if a triplet with given sum exists in BST
- Check if there exists any sub-sequence in a string which is not palindrome
- Check if a number exists with X divisors out of which Y are composite
- Check if there exists a prime number which gives Y after being repeatedly subtracted from X
- Minimum number of moves after which there exists a 3X3 coloured square
- Check if there exists a permutation of given string which doesn't contain any monotonous substring
- Check if alternate path exists from U to V with smaller individual weight in a given Graph
- Queries to check if string B exists as substring in string A
- Count of same length Strings that exists lexicographically in between two given Strings
- Find all divisors of N2 using N
- Find minimum x such that (x % k) * (x / k) == n
- Find all triplets with zero sum
- Find a triplet that sum to a given value
- Find sum of a[i]%a[j] for all valid pairs
- Find the permutation p from the array q such that q[i] = p[i+1] - p[i]
- Find the number of pairs (a, b) such that a % b = K
- Program to find covariance
- Find the Number which contain the digit d
- Find the number of Chicks in a Zoo at Nth day
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.