- Valid Anagram
A hash table can be used to efficiently determine if two strings are anagrams by counting character frequencies. By storing the frequency of each character from the first string and then decrementing the count for each character found in the second string, we can verify if all counts return to zero.
class Solution {
public:
bool isAnagram(string str1, string str2) {
if (str1.length() != str2.length()) {
return false;
}
vector<int> charFrequency(26, 0);
for (char c : str1) {
charFrequency[c - 'a']++;
}
for (char c : str2) {
charFrequency[c - 'a']--;
}
for (int count : charFrequency) {
if (count != 0) {
return false;
}
}
return true;
}
};
</int>
- Intersection of Two Arrays
To find the intersection of two arrays, we can leverage the constant-time lookup property of a hash set. By inserting all elements of one array into a set, we can then iterate through the second array and check for the presence of each element in the set. The set inherently handles duplicates, ensuring the result contains only unique values.
class Solution {
public:
vector<int> intersection(vector<int>& firstArray, vector<int>& secondArray) {
unordered_set<int> firstSet(firstArray.begin(), firstArray.end());
unordered_set<int> resultSet;
for (int num : secondArray) {
if (firstSet.count(num)) {
resultSet.insert(num);
}
}
return vector<int>(resultSet.begin(), resultSet.end());
}
};
</int></int></int></int></int></int>
- Happy Number
The "happy number" problem can be solved by detecting cycles. We use a hash set to store numbers we have encountered during the iterative process of summing the squares of digits. If we encounter a number that is already in the set, a cycle is detected, and the number is not happy. If the process reaches 1, the number is happy.
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> seenValues;
while (n != 1) {
if (seenValues.find(n) != seenValues.end()) {
return false;
}
seenValues.insert(n);
int sum = 0;
int currentValue = n;
while (currentValue > 0) {
int digit = currentValue % 10;
sum += digit * digit;
currentValue /= 10;
}
n = sum;
}
return true;
}
};
</int>
- Two Sum
For the two-sum problem, a hash map is ideal for tracking numbers and their indices as we iterate through the array. For each number, we calculate its complement (target - current number) and check if this complement has already been seen. If it has, we have found the pair of indices that sum to the target.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int int=""> valueToIndex;
for (int i = 0; i < nums.size(); ++i) {
int complement = target - nums[i];
if (valueToIndex.find(complement) != valueToIndex.end()) {
return {valueToIndex[complement], i};
}
valueToIndex[nums[i]] = i;
}
return {};
}
};
</int></int></int>