Anagram Check Techniques in DSA C++ - Time & Space Complexity
We want to understand how the time needed to check if two words are anagrams changes as the words get longer.
How does the method we use affect the speed when input size grows?
Analyze the time complexity of the following code snippet.
bool areAnagrams(string s1, string s2) {
if (s1.length() != s2.length()) return false;
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
return s1 == s2;
}
This code checks if two strings are anagrams by sorting both and comparing them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting each string using a sorting algorithm.
- How many times: Sorting runs twice, once for each string, each over n characters.
Sorting takes more time as the string length grows, roughly n log n steps for each string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 2 * 10 * log2(10) ≈ 66 steps |
| 100 | About 2 * 100 * log2(100) ≈ 1328 steps |
| 1000 | About 2 * 1000 * log2(1000) ≈ 19931 steps |
Pattern observation: Operations grow faster than the input size but slower than the square of input size.
Time Complexity: O(n log n)
This means the time to check anagrams grows a bit faster than the length of the strings but not as fast as checking every pair.
[X] Wrong: "Sorting both strings takes linear time because they are just arrays of characters."
[OK] Correct: Sorting is not just looking at each character once; it involves comparing and rearranging many times, which takes more than linear time.
Knowing how sorting affects time helps you choose the best method to check anagrams and explain your choice clearly in interviews.
"What if we used a frequency count array instead of sorting? How would the time complexity change?"
Practice
Solution
Step 1: Understand what an anagram means
An anagram means two strings contain the same characters with the same frequency, but possibly in different orders.Step 2: Identify the key condition for anagram check
The key condition is that both strings must have the same characters appearing the same number of times.Final Answer:
Both strings have the same characters with the same frequency -> Option AQuick Check:
Anagram = Same characters & frequency [OK]
- Only checking string length
- Ignoring character frequency
- Assuming order matters
- Checking only first character
s to help check an anagram?Solution
Step 1: Identify correct sorting syntax for std::string
For std::string, sorting is done using iterators:s.begin()ands.end().Step 2: Check each option for correctness
std::sort(s.begin(), s.end()); usesstd::sort(s.begin(), s.end());which is correct. sort(s, s+length); and C use pointer arithmetic which is invalid for std::string. sort(s.begin(), s.end(), compare); uses a comparator but is incomplete without defining it.Final Answer:
std::sort(s.begin(), s.end()); -> Option AQuick Check:
Sort string with iterators = std::sort(s.begin(), s.end()) [OK]
- Using pointer arithmetic on std::string
- Forgetting std:: namespace
- Using incomplete comparator
- Sorting only part of the string
std::string s1 = "listen"; std::string s2 = "silent"; std::sort(s1.begin(), s1.end()); std::sort(s2.begin(), s2.end()); if (s1 == s2) std::cout << "Anagrams"; else std::cout << "Not Anagrams";
Solution
Step 1: Sort both strings
After sorting, s1 becomes "eilnst" and s2 becomes "eilnst".Step 2: Compare sorted strings
Since both sorted strings are equal, the conditions1 == s2is true, so it prints "Anagrams".Final Answer:
Anagrams -> Option BQuick Check:
Sorted strings equal = Anagrams [OK]
- Not sorting strings before comparison
- Confusing output with original strings
- Assuming order matters
- Ignoring case sensitivity
bool areAnagrams(std::string s1, std::string s2) {
if (s1.length() != s2.length()) return false;
std::sort(s1.begin(), s1.end());
std::sort(s2.begin(), s2.end());
return s1.compare(s2);
}Solution
Step 1: Understand std::string::compare return type
The compare function returns 0 if strings are equal, else non-zero integer.Step 2: Check return type of function
The function returns bool but returns s1.compare(s2) which is int, so it will not return correct boolean value.Final Answer:
Using s1.compare(s2) returns int, not bool -> Option DQuick Check:
compare() returns int, need == 0 for bool [OK]
- Returning compare() directly as bool
- Ignoring header includes
- Passing strings by value unnecessarily
- Incorrect length check logic
Solution
Step 1: Analyze sorting approach
Sorting takes O(n log n) time, which is good but not optimal for fixed character set.Step 2: Analyze frequency array approach
Using a frequency array of size 26 counts characters in O(n) time, which is faster and uses constant extra space.Step 3: Compare other options
Nested loops are inefficient O(n^2). Converting case does not check anagram correctness.Final Answer:
Use a frequency array of size 26 to count characters -> Option CQuick Check:
Frequency array = O(n) efficient anagram check [OK]
- Using sorting for large strings unnecessarily
- Using nested loops causing slow performance
- Ignoring character set constraints
- Assuming case conversion solves anagram check
Ready to prove it?
Pass the test and this pattern moves unknown
