Opening the reading…
Opening the reading…
HASHING › IMPLEMENTARY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Rearranging letters changes their positions but never changes how many times each letter appears. Therefore, t is an anagram of s exactly when both strings have the same count for every lowercase letter. The order of characters is irrelevant; the 26 frequencies are the complete information needed to decide the answer.
First add one to the count for every character in s. Then subtract one for every character in t. If a subtraction makes a count negative, t has already used some letter more times than s contains it, so the strings cannot match. If no count becomes negative and the lengths were equal, every count finishes at zero.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | Each string is scanned once, and each character causes one array access and one arithmetic update. The two passes examine 2n characters, which is linear, and no character is revisited by another data structure. |
| Space | O(1) extra | The counter always contains exactly 26 integers, independent of n. The returned boolean is not working memory, and there is no output collection to count. The bound stays O(1) even for the largest or most uneven letter distributions because the alphabet size is fixed. |
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
vector<int> count(26, 0);
for (char c : s) {
count[c - 'a']++;
}
for (char c : t) {
count[c - 'a']--;
if (count[c - 'a'] < 0) return false;
}
return true;
}
};The early negative check is safe because counts begin with exactly the supply from s. Once one slot drops below zero, t has already used too many copies of that letter; the remaining characters cannot make that particular shortage disappear. The equal-length check then supplies the other half of the proof: without it, t could use fewer letters and still leave unused positive counts.
A competent alternative is to sort both strings and compare the sorted results. Sorting removes the original order from both strings, so equal results mean the same letters appear with the same multiplicities. This is merely a different arrangement, not an optimisation: it uses O(n log n) time instead of O(n), while using O(n) additional storage for the copied or sorted string data.
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};