1. Linear Search and Replace
Intuition
Iterate through each character in ransomNote. Find its first index in magazine. If not found, return false. If found, remove it from magazine and continue. Return true.
When to apply: Basic baseline comparison.
Algorithm
- If
ransomNote.length > magazine.length: return false. - Convert
magazineto a mutable structure. - For
cinransomNote: - Find index of
cinmagazine. - If not found: return false.
- Erase character at index from
magazine. - Return true.
Linear Search and Character Removal Trace
2 of 2 questions left todayObservation: Find first 'a' in magazine
Observation: Find first 'a' in magazine.
Decision: Match found at index 0. Remove it so it cannot be reused.
Invariant: One 'a' fulfilled; magazine reduces to "ab".
#include <iostream>#include <string> class Solution {public: bool canConstruct(std::string ransomNote, std::string magazine) { if (ransomNote.size() > magazine.size()) return false; for (char c : ransomNote) { size_t pos = magazine.find(c); if (pos == std::string::npos) return false; magazine.erase(pos, 1); } return true; }}; int main() { Solution sol; std::cout << (sol.canConstruct("a", "b") ? "true" : "false") << std::endl; // false std::cout << (sol.canConstruct("aa", "aab") ? "true" : "false") << std::endl; // true return 0;}Time & Space Complexity
- Time complexity:
O(N * M)— N searches, each scanning through M characters. - Space complexity:
O(M)
Why Brute Force Doesn't Scale:
On-the-fly decrementing terminates on first violation.
26-integer stack array.