Back to Arrays & Hashing
Easy
Valid Anagram
Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Examples
Input:s = "anagram", t = "nagaram"
Output:true
Both strings contain the same characters in the exact same frequencies.
Input:s = "rat", t = "car"
Output:false
The characters do not match.
Constraints
1 <= s.length, t.length <= 5 * 10^4s and t consist of lowercase English letters.
Approach
If two strings are anagrams, sorting their characters will produce identical strings. We can convert both strings to character arrays, sort them, and compare the results.
Complexity Analysis
Time Complexity
O(n log n)
Space Complexity
O(1) or O(n)
Sorting takes O(n log n) time. Space complexity depends on the sorting algorithm; often O(n) space is needed to convert strings to mutable arrays.
Solution.java
class Solution { public boolean isAnagram(String s, String t) { // If lengths differ, they cannot be anagrams if (s.length() != t.length()) return false; char[] sChars = s.toCharArray(); char[] tChars = t.toCharArray(); // Sort both arrays Arrays.sort(sChars); Arrays.sort(tChars); // Compare the sorted arrays return Arrays.equals(sChars, tChars); }}