This approach involves sorting both strings and comparing them. If they are anagrams, both sorted strings will be identical since an anagram is defined as a rearrangement of letters. The time complexity mainly depends on the sorting step, which is O(n log n), where n is the length of the strings. Space complexity is O(1) if sorting is done in-place, otherwise O(n) with additional space for sorted copies.
Time Complexity: O(n log n), Space Complexity: O(n) due to sorting overhead.
1function isAnagram(s, t) {
2 if (s.length !== t.length) {
3 return false;
4 }
5 const sortedS = s.split('').sort().join('');
6 const sortedT = t.split('').sort().join('');
7 return sortedS === sortedT;
8}
9
10let s = 'anagram';
11let t = 'nagaram';
12console.log(isAnagram(s, t));
Check string lengths first. Use split()
to convert strings into arrays, sort()
to sort, and join()
to revert arrays back to strings before comparing both strings for equality.
This approach uses two arrays (or hashmaps for more general cases) to count the frequency of each character in both strings. Since the problem constraints specify lowercase English letters, array indices (0-25) can be used to count character occurrences.
Time Complexity: O(n), Space Complexity: O(1) as the count array is fixed in size.
1public class AnagramCheck {
2 public static boolean isAnagram(String s, String t) {
3 if (s.length() != t.length()) {
4 return false;
5 }
6 int[] count = new int[26];
7 for (int i = 0; i < s.length(); i++) {
8 count[s.charAt(i) - 'a']++;
9 count[t.charAt(i) - 'a']--;
10 }
11 for (int c : count) {
12 if (c != 0) {
13 return false;
14 }
15 }
16 return true;
17 }
18
19 public static void main(String[] args) {
20 String s = "anagram";
21 String t = "nagaram";
22 System.out.println(isAnagram(s, t));
23 }
24}
Frequency counters are updated and evaluated at each character iteration. Balanced elements imply identical character distributions across both strings, fulfilling anagram conditions.