1. Iterative String Pair Replacement
Intuition
While string contains "()", "{}", or "[]", replace all occurrences with the empty string "". If the resulting string is empty, return true; else false.
When to apply: Basic baseline conceptual solution.
Algorithm
- While
s.includes('()') || s.includes('{}') || s.includes('[]'): - Replace
"()"with"". - Replace
"{}"with"". - Replace
"[]"with"". - Return
s.empty().
Iterative Adjacent Pair Replacement Trace
2 of 2 questions left todayObservation: A string of brackets is valid if adjacent matched pairs can be iteratively canceled out
Observation: A string of brackets is valid if adjacent matched pairs can be iteratively canceled out.
Decision: Repeatedly replace "()", "[]", "{}" with "" until no pairs remain.
Invariant: Length decreases by 2 on each replacement.
#include <iostream>#include <string> class Solution {public: bool isValid(std::string s) { if (s.size() % 2 != 0) return false; size_t pos; while ((pos = s.find("()")) != std::string::npos || (pos = s.find("{}")) != std::string::npos || (pos = s.find("[]")) != std::string::npos) { s.erase(pos, 2); } return s.empty(); }}; int main() { Solution sol; std::cout << (sol.isValid("()[]{}") ? "true" : "false") << std::endl; // true std::cout << (sol.isValid("(]") ? "true" : "false") << std::endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Up to N / 2 replacements, each taking O(N) string scanning and copying. - Space complexity:
O(N)
Why Brute Force Doesn't Scale:
Pushing expected closing character eliminates hash map / switch lookup on pop.
Preallocated dynamic array stack.