Leetcode 242. Valid Anagram Sure! Let’s go through the problem-solving process for “242. Valid Anagram” from LeetCode.
Given two strings s
and t
, write a function to determine if t
is an anagram of s
.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
Assuming we have clarity and no further questions, we can move on to the strategy.
An anagram requires that both strings, when sorted, look the same. Thus, the character counts should match for both strings.
There are two primary ways to solve this problem:
We will use the Frequency Counting Method as it generally offers better performance.
The Sorting Method would involve O(n log n)
time complexity due to sorting. The Frequency Counting Method operates in O(n)
time for counting and comparing, where n
is the length of the strings.
Here is the solution using the Frequency Counting Method:
#include <iostream>
#include <vector>
#include <string>
bool isAnagram(std::string s, std::string t) {
if (s.size() != t.size()) {
return false;
}
std::vector<int> count(26, 0); // Since there are 26 lowercase letters
for (int i = 0; i < s.size(); ++i) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int i = 0; i < 26; ++i) {
if (count[i] != 0) {
return false;
}
}
return true;
}
int main() {
std::string s = "anagram";
std::string t = "nagaram";
if (isAnagram(s, t)) {
std::cout << "The strings are anagrams." << std::endl;
} else {
std::cout << "The strings are not anagrams." << std::endl;
}
return 0;
}
count
of size 26 (for each letter of the alphabet) to keep track of character frequencies.s
and decrementing for characters in t
.By following this approach, we ensure an efficient O(n)
time complexity solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?