VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-permutation-of-pattern-is-substring/

⇱ Check if Permutation of Pattern is Substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if Permutation of Pattern is Substring

Last Updated : 23 Jul, 2025

Given two strings txt and pat having lowercase letters, the task is to check if any permutation of pat is a substring of txt.

Examples:

Input: txt = "geeks", pat = "eke"
Output: true
Explanation: "eek" is a permutation of "eke" which exists in "geeks".

Input: txt = "programming", pat = "rain"
Output: false
Explanation: No permutation of "rain" exists as a substring in "programming".

[Naive Approach] Checking all possible substrings

The idea is to iterate over all possible substrings of txt having the same length as pat. For each substring of txt, check if pat is a permutation of the substring. Two strings are said to be permutations of each other if they contain the same characters with the same frequencies, but possibly in a different order. So, we can match the frequency of each character in both the strings to check if they are permutations of each other or not.


Output
true

Time Complexity: O(n*m), where n is the length of txt and m is the length of pat.
Auxiliary Space: O(MAX_CHAR), where MAX_CHAR = 26 as txt and pat have lowercase letters only.

[Expected Approach] Using Sliding Window

The idea is similar to the previous approach where we check if pat is a permutation of any substring of txt but instead of comparing each substring from the beginning, we can use Sliding Window Technique and slide a window of the same size as pat. When a new character is added to the window, we increase its frequency by 1 and when a character is removed from the window, we decrease its frequency by 1.


Output
true

Time Complexity: O(n*MAX_CHAR), where n is the length of txt and MAX_CHAR = 26 as txt and pat have lowercase letters only.
Auxiliary Space: O(1)

Comment
Article Tags: