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.
1import java.util.Arrays;
2
3public class AnagramCheck {
4 public static boolean isAnagram(String s, String t) {
5 if (s.length() != t.length()) {
6 return false;
7 }
8 char[] sArray = s.toCharArray();
9 char[] tArray = t.toCharArray();
10 Arrays.sort(sArray);
11 Arrays.sort(tArray);
12 return Arrays.equals(sArray, tArray);
13 }
14
15 public static void main(String[] args) {
16 String s = "anagram";
17 String t = "nagaram";
18 System.out.println(isAnagram(s, t));
19 }
20}
First, verify length equality. Turn strings into character arrays, apply Arrays.sort
, and then use Arrays.equals
to check for equality of both sorted arrays.
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.
1#include <iostream>
2#include <vector>
3
4bool isAnagram(std::string s, std::string t) {
5 if (s.size() != t.size()) {
6 return false;
7 }
8 std::vector<int> count(26, 0);
9 for (int i = 0; i < s.size(); ++i) {
10 count[s[i] - 'a']++;
11 count[t[i] - 'a']--;
12 }
13 for (int c : count) {
14 if (c != 0) {
15 return false;
16 }
17 }
18 return true;
19}
20
21int main() {
22 std::string s = "anagram";
23 std::string t = "nagaram";
24 std::cout << (isAnagram(s, t) ? "true" : "false") << std::endl;
25 return 0;
26}
Character frequency is tracked via a vector, altered by the simultaneous iteration over both strings. Zero variance in all elements confirms an anagram status.