Anagram Check Techniques in DSA Rust - Time & Space Complexity
Checking if two words are anagrams means seeing if they have the same letters in any order.
We want to know how the time needed changes as the words get longer.
Analyze the time complexity of the following code snippet.
fn are_anagrams(s1: &str, s2: &str) -> bool {
if s1.len() != s2.len() {
return false;
}
let mut chars1: Vec = s1.chars().collect();
let mut chars2: Vec = s2.chars().collect();
chars1.sort_unstable();
chars2.sort_unstable();
chars1 == chars2
}
This code checks if two strings are anagrams by sorting their characters and comparing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the characters of each string.
- How many times: Sorting runs twice, once per string, each over n characters.
Sorting takes more time as the string length grows, roughly n log n steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 * log(10) ≈ 33 steps per sort, done twice |
| 100 | About 100 * log(100) ≈ 664 steps per sort, done twice |
| 1000 | About 1000 * log(1000) ≈ 9966 steps per sort, done twice |
Pattern observation: As input grows, operations grow a bit faster than linearly, because sorting is involved.
Time Complexity: O(n log n)
This means the time to check anagrams grows a bit faster than the length of the strings because sorting is the main work.
[X] Wrong: "Comparing characters one by one without sorting is always faster."
[OK] Correct: Without sorting or counting, you might miss differences or need to check many pairs, which can be slower or more complex.
Understanding how sorting affects time helps you explain your choices clearly and shows you know how to handle string problems efficiently.
"What if we used a character count array instead of sorting? How would the time complexity change?"
Practice
Solution
Step 1: Understand anagram definition
Anagrams are words or phrases made by rearranging letters of another, so character frequency must match.Step 2: Compare character frequencies
Checking if both strings have the same characters with the same counts confirms they are anagrams.Final Answer:
Both strings have the same characters with the same frequency -> Option AQuick Check:
Anagram check = same characters & frequency [OK]
- Only comparing string lengths
- Ignoring character frequency
- Checking only first characters
s to help check anagrams?Solution
Step 1: Collect characters into a vector
Uses.chars().collect()to get a vector of characters from the string.Step 2: Sort the vector in place
Callchars.sort()to sort characters alphabetically for comparison.Final Answer:
let mut chars: Vec<char> = s.chars().collect(); chars.sort(); -> Option AQuick Check:
Collect chars then sort vector [OK]
- Trying to sort string directly
- Using non-existent sorted() method
- Calling sort() on &str instead of Vec<char>
fn main() {
let s1 = "listen";
let s2 = "silent";
let mut v1: Vec<char> = s1.chars().collect();
let mut v2: Vec<char> = s2.chars().collect();
v1.sort();
v2.sort();
println!("{}", v1 == v2);
}Solution
Step 1: Convert strings to char vectors and sort
Both "listen" and "silent" are converted to vectors and sorted alphabetically.Step 2: Compare sorted vectors
Sorted vectors for both strings become ['e', 'i', 'l', 'n', 's', 't'], so they are equal.Final Answer:
true -> Option BQuick Check:
Sorted chars equal means anagrams [OK]
- Expecting false because strings differ
- Confusing sorting with original order
- Thinking println! prints vectors directly
fn are_anagrams(s1: &str, s2: &str) -> bool {
let mut v1: Vec<char> = s1.chars().collect();
let mut v2: Vec<char> = s2.chars().collect();
v1.sort();
v2.sort();
v1 == v2
}
fn main() {
println!("{}", are_anagrams("abc", "cba"));
}Solution
Step 1: Review vector creation and sorting
Vectors are mutable and sorted correctly usingv1.sort()andv2.sort().Step 2: Check comparison and usage
Comparing vectors with == is valid and returns true if sorted characters match.Final Answer:
No bug, function works correctly -> Option DQuick Check:
Sorting and comparing vectors works fine [OK]
- Thinking == can't compare vectors
- Assuming length check is mandatory
- Forgetting mut keyword (but it's present here)
Solution
Step 1: Normalize strings by lowering case and removing spaces
Convert both strings to lowercase and remove all spaces to ignore case and whitespace differences.Step 2: Sort characters and compare
Sort the cleaned character vectors and compare them to confirm anagram status.Final Answer:
Convert both strings to lowercase, remove spaces, then sort and compare characters -> Option CQuick Check:
Normalize case and spaces before sorting [OK]
- Ignoring case differences
- Not removing spaces
- Comparing raw strings directly
Ready to prove it?
Pass the test and this pattern moves unknown
