1. Sort Both Strings
Intuition
If s and t have different lengths, return false. Sort characters of s and sort characters of t. If sorted s equals sorted t, return true; otherwise, return false.
When to apply: Basic baseline comparison.
Algorithm
- If
s.length != t.length: return false. - Sort
s. - Sort
t. - Return
s == t.
Sorting Both Strings & Direct Equality Trace
2 of 2 questions left todayObservation: Compare string lengths
Observation: Compare string lengths. s.length == t.length == 7.
Decision: If lengths differed, they could never be anagrams. Since equal, continue to sorting.
Invariant: Candidate pair has equal size.
#include <iostream>#include <string>#include <algorithm> class Solution {public: bool isAnagram(std::string s, std::string t) { if (s.size() != t.size()) return false; std::sort(s.begin(), s.end()); std::sort(t.begin(), t.end()); return s == t; }}; int main() { Solution sol; std::cout << (sol.isAnagram("anagram", "nagaram") ? "true" : "false") << std::endl; // true std::cout << (sol.isAnagram("rat", "car") ? "true" : "false") << std::endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Sorting N characters takes O(N log N) time. - Space complexity:
O(1) or O(N)
Why Brute Force Doesn't Scale:
Single loop computes increments and decrements simultaneously.
26-element integer array allocated on the stack.