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 <iostream>
2#include <algorithm>
3
4bool isAnagram(std::string s, std::string t) {
5 if (s.size() != t.size()) {
6 return false;
7 }
8 std::sort(s.begin(), s.end());
9 std::sort(t.begin(), t.end());
10 return s == t;
11}
12
13int main() {
14 std::string s = "anagram";
15 std::string t = "nagaram";
16 std::cout << (isAnagram(s, t) ? "true" : "false") << std::endl;
17 return 0;
18}
We check string lengths initially. Then, we use the std::sort
function from the C++ STL to sort both strings and compare them. If they are identical post-sort, 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.
1def is_anagram(s: str, t: str) -> bool:
2 if len(s) != len(t):
3 return False
4 count = [0] * 26
5 for i in range(len(s)):
6 count[ord(s[i]) - ord('a')] += 1
7 count[ord(t[i]) - ord('a')] -= 1
8 return all(x == 0 for x in count)
9
10s = "anagram"
11t = "nagaram"
12print(is_anagram(s, t))
Using Python's list for counting the occurrence of each letter, this approach confirms anagrams by net-zero arrays post-evaluation, connoting equivalent character makeup.