1. Substring Sorting Brute Force
Intuition
Sort string p once. Then iterate index i from 0 to s.length - p.length. Extract the substring s.substr(i, p.length), sort its characters, and compare with sorted p. If they are identical, record index i.
When to apply: As an initial baseline concept before explaining sliding window.
Algorithm
- If
s.length < p.length, return empty list. - Sort
pto getsortedP. - Loop
ifrom0tos.length - p.length: - Extract substring of length
p.lengthstarting ati. - Sort the substring.
- If sorted substring equals
sortedP, pushito results. - Return results list.
Substring Sorting Brute Force
2 of 2 questions left todayObservation: Target $p = 'abc'$ has length $M = 3$ and sorts to 'abc'
Observation: Target p = abc has length M = 3 and sorts to 'abc'. Inspect window s[0..2] = 'cba'.
Decision: Sorting 'cba' yields 'abc'. Exactly matches target; record start index 0.
Invariant: Two strings are anagrams if and only if their sorted versions are identical.
#include <iostream>#include <string>#include <vector>#include <algorithm> class Solution {public: std::vector<int> findAnagrams(std::string s, std::string p) { std::vector<int> res; int n = s.size(), m = p.size(); if (n < m) return res; std::string sortedP = p; std::sort(sortedP.begin(), sortedP.end()); for (int i = 0; i <= n - m; ++i) { std::string sub = s.substr(i, m); std::sort(sub.begin(), sub.end()); if (sub == sortedP) { res.push_back(i); } } return res; }}; int main() { Solution sol; auto ans = sol.findAnagrams("cbaebabacd", "abc"); for (int x : ans) std::cout << x << " "; // 0 6 std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O((N - M + 1) * M log M)— Extracting and sorting M characters for each of the (N - M + 1) windows takes O(N * M log M). - Space complexity:
O(M) for substring copies
Why Brute Force Doesn't Scale:
Tracking the number of matching frequencies avoids even the 26-element array loop.
Using two 26-element primitive arrays requires O(1) space and zero heap allocations.