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.
1#include <stdio.h>
2#include <string.h>
3#include <stdbool.h>
4
5int compare(const void* a, const void* b) {
6 return *(char*)a - *(char*)b;
7}
8
9bool isAnagram(char * s, char * t) {
10 if (strlen(s) != strlen(t)) {
11 return false;
12 }
13 qsort(s, strlen(s), sizeof(char), compare);
14 qsort(t, strlen(t), sizeof(char), compare);
15 return strcmp(s, t) == 0;
16}
17
18int main() {
19 char s[] = "anagram";
20 char t[] = "nagaram";
21 printf("%s\n", isAnagram(s, t) ? "true" : "false");
22 return 0;
23}
We first check if the lengths of the strings are equal; if not, they cannot be anagrams. We use qsort to sort both strings. Then, we use strcmp to check if the sorted versions are equal. If they are, it means 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.
1function isAnagram(s, t) {
2 if (s.length !== t.length) {
3 return false;
4 }
5 const count = Array(26).fill(0);
6 for (let i = 0; i < s.length; i++) {
7 count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
8 count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--;
9 }
10 return count.every(c => c === 0);
11}
12
13let s = 'anagram';
14let t = 'nagaram';
15console.log(isAnagram(s, t));
Leveraging JavaScript arrays for provisional frequency analysis, the resolution calculates balance by comparing all elements for zero values. Such uniformity in zeros confirms anagrams.