Anagram Check Techniques in DSA Java - 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 work grow when the input size increases?
Analyze the time complexity of the following code snippet.
public boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
int[] counts = new int[26];
for (int i = 0; i < s1.length(); i++) {
counts[s1.charAt(i) - 'a']++;
counts[s2.charAt(i) - 'a']--;
}
for (int count : counts) {
if (count != 0) return false;
}
return true;
}
This code checks if two strings are anagrams by counting character frequencies.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop that runs through both strings simultaneously to count characters.
- How many times: Runs once for each character in the strings (n times).
- Secondary operation: Another loop that checks the counts array of fixed size 26.
- How many times: Always 26 times, independent of input size.
As the strings get longer, the main loop runs more times, directly proportional to the string length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps for counting + 26 checks |
| 100 | About 100 steps for counting + 26 checks |
| 1000 | About 1000 steps for counting + 26 checks |
Pattern observation: The work grows linearly with input size because the counting loop depends on string length, while the checking loop is constant.
Time Complexity: O(n)
This means the time to check anagrams grows directly with the length of the strings.
[X] Wrong: "Sorting both strings is always faster than counting characters."
[OK] Correct: Sorting takes more time (O(n log n)) compared to counting (O(n)), so counting is usually faster for anagram checks.
Understanding how to check anagrams efficiently shows you can choose the best approach for a problem, a key skill in interviews and real projects.
"What if the input strings contain Unicode characters beyond 'a' to 'z'? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of anagrams
Anagrams are words or phrases made by rearranging the letters of another, using all original letters exactly once.Step 2: Compare character sets
If two strings have the same characters with the same frequency, they are anagrams regardless of order.Final Answer:
They contain the same characters in any order -> Option DQuick Check:
Anagrams = same characters any order [OK]
- Thinking same length means anagrams
- Only comparing first or last characters
- Ignoring character frequency
s1 and s2 are anagrams using sorting?Solution
Step 1: Convert strings to char arrays and sort
We must convert strings to char arrays becauseArrays.sortworks on arrays, not strings.Step 2: Compare sorted arrays for equality
After sorting, if arrays are equal, strings are anagrams. UseArrays.equalsto compare arrays.Final Answer:
char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); Arrays.sort(a1); Arrays.sort(a2); return Arrays.equals(a1, a2); -> Option AQuick Check:
Sort char arrays and compare arrays [OK]
- Sorting strings directly without converting to char arrays
- Using equals() on unsorted strings
- Comparing only lengths
String s1 = "listen"; String s2 = "silent"; char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); Arrays.sort(a1); Arrays.sort(a2); System.out.println(Arrays.equals(a1, a2));
Solution
Step 1: Convert and sort both strings
Both strings "listen" and "silent" are converted to char arrays and sorted. Sorted arrays become ['e','i','l','n','s','t'] for both.Step 2: Compare sorted arrays
Since sorted arrays are identical,Arrays.equals(a1, a2)returns true.Final Answer:
true -> Option CQuick Check:
Sorted arrays match = true [OK]
- Assuming order matters without sorting
- Confusing equals() on strings with arrays
- Forgetting to sort arrays
public boolean isAnagram(String s1, String s2) {
if (s1.length() != s2.length()) return false;
char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
return a1.equals(a2);
}Solution
Step 1: Understand array equality in Java
Usinga1.equals(a2)compares if both arrays are the same object, not their contents.Step 2: Use correct method to compare arrays
To compare contents, useArrays.equals(a1, a2)instead ofa1.equals(a2).Final Answer:
Using a1.equals(a2) compares references, not content -> Option AQuick Check:
Use Arrays.equals() for array content comparison [OK]
- Using equals() on arrays instead of Arrays.equals()
- Ignoring length check
- Returning wrong data type
Solution
Step 1: Normalize strings by removing spaces and converting to lowercase
Removing spaces and converting to lowercase ensures uniform comparison ignoring case and spaces.Step 2: Sort char arrays and compare
After normalization, convert to char arrays, sort them, and compare to check anagram status.Final Answer:
Remove spaces, convert to lowercase, then sort and compare char arrays -> Option BQuick Check:
Normalize then sort and compare [OK]
- Not removing spaces before comparison
- Ignoring case differences
- Only comparing lengths or first characters
Ready to prove it?
Pass the test and this pattern moves unknown
