Permutation in Given String

Program to solve Permutation in a given String Problem

You are given two strings, s1 and s2, which only contain lowercase letters.

Your task is to determine if any permutation of string s1 can be found as a substring within string s2. 

In other words, you need to check if there exists a rearranged version of s1 that appears as a contiguous part of s2. If such a permutation exists, return true; otherwise, return false.

Permutation in a given String

Explanation : The substring “cab” is a permutation of “abc” and is present in “lecabee”.

Constraints:

  • 1 <= s1.length, s2.length <= 1000

Program to solve Permutation in a given String Solution

Recommendation for Time and Space Complexity –You should aim for a solution with O(n) time and O(1) space, where n is the maximum of the lengths of the two strings.

Hints for solving problems

Hint 1 :

A brute force solution would be to check every substring of s2 with s1 by sorting s1 as well as the substring of s2. This would be an O(n^2) solution. Can you think of a better way? Maybe we can use the freqency of the characters of both the strings as we did in checking anagrams.

Hint 2 :

We return false if the length of s1 is greater than the length of s2. To count the frequency of each character in a string, we can simply use an array of size O(26), since the character set consists of a through z (26 continuous characters). Which algorithm can we use now?

There are mainly 3 approach to solve this problem-

  1. Brute Force Method
  2. Hash Table Method
  3. Sliding Window Method

1. Brute Force Method

Generate all permutations of the given string s1 and check if any of these permutations is a substring of s2. This method is not efficient due to the factorial time complexity.

  • Time complexity: O(n^3 logn)
  • Space complexity: O(n)

Code

2. Hash Table Method

Use a frequency map (hash table) for s1 and compare it with the frequency map of substrings of the same length in s2 by sliding the window.

  • Time complexity: O(n*m)
  • Space complexity: O(1)

where n is the length of the string1 and m is the length of string2.

Code

3. Sliding Window Method

Maintain a sliding window of size equal to s1 in s2 and use two frequency arrays (or hash maps) to efficiently compare character frequencies, updating the window dynamically.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles