LeetCode 242: Valid Anagram
LeetCode 242 Solution Explanation
Explanation
To solve this problem, we can first check if the lengths of the two strings are different. If they are not, we can create a frequency map for each character in both strings. Then, we compare the frequency maps to check if they are equal. If they are equal, it means the two strings are anagrams of each other.
Algorithm:
- Check if the lengths of strings
s
andt
are different. If they are, return false. - Create frequency maps for characters in strings
s
andt
. - Compare the frequency maps. If they are equal, return true; otherwise, return false.
Time Complexity
The time complexity of this solution is O(n), where n is the length of the input strings s
and t
.
Space Complexity
The space complexity of this solution is O(1) because we are using a fixed-size array to store the frequency of characters.
LeetCode 242 Solutions in Java, C++, Python
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
for (char c : t.toCharArray()) {
count[c - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}
}
Interactive Code Editor for LeetCode 242
Improve Your LeetCode 242 Solution
Use the editor below to refine the provided solution for LeetCode 242. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...