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.
1using System;
2
3public class AnagramCheck {
4 public static bool 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 Array.Sort(sArray);
11 Array.Sort(tArray);
12 return new string(sArray) == new string(tArray);
13 }
14
15 public static void Main() {
16 string s = "anagram";
17 string t = "nagaram";
18 Console.WriteLine(IsAnagram(s, t));
19 }
20}
Check if the lengths match; if not, immediately return false. Convert strings to character arrays, sort both, then form strings again to compare for equality. If true, t
is an anagram of s
.
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 <stdio.h>
2#include <stdbool.h>
3#include <string.h>
4
5bool isAnagram(char * s, char * t) {
6 if (strlen(s) != strlen(t)) {
7 return false;
8 }
9 int count[26] = {0};
10 for (int i = 0; i < strlen(s); i++) {
11 count[s[i] - 'a']++;
12 count[t[i] - 'a']--;
13 }
14 for (int i = 0; i < 26; i++) {
15 if (count[i] != 0) {
16 return false;
17 }
18 }
19 return true;
20}
21
22int main() {
23 char s[] = "anagram";
24 char t[] = "nagaram";
25 printf("%s\n", isAnagram(s, t) ? "true" : "false");
26 return 0;
27}
Iterate over both strings simultaneously, adjusting a count array to track net character frequency. If all counts are zero at the end, t
is an anagram of s
.