1. Brute Force All Substrings
Intuition
For each start index i and end index j: compute character counts of s[i...j]. If all characters of t are present with sufficient count, check if j - i + 1 < minLen. Return the smallest matching substring.
When to apply: Basic initial explanation.
Algorithm
- Populate
targetFreqfort. - Loop
ifrom 0 ton - 1: - Loop
jfromiton - 1: - If
s[i...j]containst:update minWindow. - Return
minWindow.
Interactive Trace
2 of 2 questions left todayrequired=3 distinct chars ('A','B','C')
required=3 distinct chars (A,B,C). Expand right until right=5: window=ADOBEC has all 3 required chars.
#include <iostream>#include <string>#include <vector> class Solution { bool isValid(const int sCount[], const int tCount[]) { for (int i = 0; i < 128; ++i) { if (sCount[i] < tCount[i]) return false; } return true; }public: std::string minWindow(std::string s, std::string t) { int n = s.size(), m = t.size(); if (n < m) return ""; int tCount[128] = {0}; for (char c : t) tCount[(unsigned char)c]++; std::string best = ""; int minLen = 1e9; for (int i = 0; i < n; ++i) { int sCount[128] = {0}; for (int j = i; j < n; ++j) { sCount[(unsigned char)s[j]]++; if (j - i + 1 < minLen && isValid(sCount, tCount)) { minLen = j - i + 1; best = s.substr(i, minLen); } } } return best; }}; int main() { Solution sol; std::cout << sol.minWindow("ADOBECODEBANC", "ABC") << std::endl; // "BANC" return 0;}Time & Space Complexity
- Time complexity:
O(N^2 * M)— Tests all N2 substrings with multi-character frequency checks. - Space complexity:
O(128)
Why Brute Force Doesn't Scale:
Tracking the number of satisfied characters with formed eliminates O(128) array comparison loops.
Using two 128-element static arrays achieves strict O(1) space with zero memory allocations.