AlgoMaster Logo

Permutation in String

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The brute-force approach involves checking all permutations of s1 and seeing if any of them is a substring of s2. Although not efficient, it helps build understanding of the problem.

  1. Generate all permutations of the string s1.
  2. Check each permutation to see if it exists as a substring in s2.

Code:

2. Sorting Each Substring

Intuition:

Since a permutation of s1 should have the same characters with the same frequency, for each substring of s2 with length s1, we check if its sorted version matches the sorted s1.

  1. Sort s1.
  2. For each possible substring of s2 with the length of s1, sort it and compare with sorted s1.

Code:

3. Sliding Window

Intuition:

The optimized approach uses a sliding window technique with two arrays (or maps) to keep track of character counts. If at any point the character counts between the current window in s2 and s1 match, we found a permutation.

  1. Use two counts arrays of size 26 (for each letter in the alphabet) for s1 and the current window.
  2. Slide over s2 with a window of the size of s1, updating the counts.
  3. If the counts match, return true.

Code: