885662. Check if Permutation is Substring
Easy
Check if Permutation is Substring
Summary
Given two strings s1 and s2, check if s2 is a permutation of a substring in s1. A permutation of a string means rearranging its characters to form another string. The problem requires identifying whether s2 can be formed by rearranging the characters within s1 into a contiguous substring.
Detailed Explanation
To solve this problem, we will use a sliding window approach to check if s2 is a permutation of any substring in s1. Here's the step-by-step breakdown:
- Initialize two pointers,
startandend, to represent the start and end indices of the sliding window. - Iterate through
s1with theendpointer until the length of the substring betweenstartandendis equal to the length ofs2. - Sort the characters in the current substring (using a sorting algorithm like QuickSort or BubbleSort) and store it in an array,
arr. - Compare
arrwith the sorted characters ofs2. If they match, it means thats2is a permutation of the current substring ins1, so returntrue. - Move the
endpointer one step forward and repeat steps 2-4 until the end ofs1is reached. - If no permutation is found, return
false.
Time complexity: O(n log n) due to sorting within each substring Space complexity: O(1) as we only use a constant amount of space
Optimized Solutions
Java
public boolean checkPermutation(String s1, String s2) {
if (s1.length() < s2.length()) return false;
for (int start = 0; start <= s1.length() - s2.length(); start++) {
int[] arr = new int[256]; // ASCII characters
for (int end = start; end < start + s2.length(); end++) {
arr[s1.charAt(end)]++;
}
boolean isPermutation = true;
for (int i = 0; i < 256; i++) {
if (arr[i] != s2.charAt(i) - 'a' + 1) {
isPermutation = false;
break;
}
}
if (isPermutation) return true;
}
return false;
}