1. Sort Every Window of Length M
Intuition
Sort s1 into sortedS1. For each index i from 0 to s2.length - s1.length: extract substring s2[i...i+M-1], sort it, and compare with sortedS1. If equal, return true.
When to apply: Basic baseline comparison.
Algorithm
- If
s1.length > s2.length: return false. sortedS1 = sort(s1).- For
ifrom 0 tos2.length - s1.length: -
sub = sort(s2.substr(i, s1.length)). - If
sub == sortedS1: return true. - Return false.
Sort Every Window of Length M
2 of 2 questions left todayObservation: Target s1 = 'ab' has length $M = 2$ and sorts to 'ab'
Observation: Target s1 = 'ab' has length M = 2 and sorts to 'ab'. Inspect initial window s2[0..1] = 'ei'.
Decision: Sort window substring: 'ei'. Compare against sorted target 'ab'. Mismatch detected.
Invariant: A substring is a permutation of s_1 if and only if their sorted character sequences are identical.
#include <iostream>#include <string>#include <algorithm> class Solution {public: bool checkInclusion(std::string s1, std::string s2) { int m = s1.size(), n = s2.size(); if (m > n) return false; std::string sortedS1 = s1; std::sort(sortedS1.begin(), sortedS1.end()); for (int i = 0; i <= n - m; ++i) { std::string sub = s2.substr(i, m); std::sort(sub.begin(), sub.end()); if (sub == sortedS1) return true; } return false; }}; int main() { Solution sol; std::cout << (sol.checkInclusion("ab", "eidbaooo") ? "true" : "false") << std::endl; // true std::cout << (sol.checkInclusion("ab", "eidboaoo") ? "true" : "false") << std::endl; // false return 0;}Time & Space Complexity
- Time complexity:
O((N - M + 1) * M log M)— Extracts and sorts N - M + 1 substrings of length M. - Space complexity:
O(M)
Why Brute Force Doesn't Scale:
Tracking matches variable eliminates the 26-element array loop.
Two 26-integer stack arrays.