Leetcode 2273. Find Resultant Array After Removing Anagrams
You are given a 0-indexed string array words
, where words[i]
consists of lowercase English letters. In one operation, you can select any index i
and remove words[i]
if words[i - 1]
and words[i]
are anagrams of each other. You need to return the resultant array after applying the operation any number of times.
words
contain duplicate strings which are not at adjacent positions?
words
can contain duplicate strings, but we only consider removal when adjacent strings are anagrams.Comparison function: We need a function to compare if two strings are anagrams. One efficient way is to sort both strings and check if they are equal.
Iteration: Iterate through the list of words and build the resultant array by only adding words that are not anagrams of the previous word in the resultant array.
Implementation Steps:
words
, and at each step, check if the current word is an anagram of the last word added to the resultant array.#include <vector>
#include <string>
#include <algorithm> // for sort
#include <iostream>
// Helper function to check if two strings are anagrams
bool areAnagrams(const std::string& s1, const std::string& s2) {
if (s1.length() != s2.length()) return false;
// Sort both strings and compare
std::string sorted_s1 = s1;
std::string sorted_s2 = s2;
std::sort(sorted_s1.begin(), sorted_s1.end());
std::sort(sorted_s2.begin(), sorted_s2.end());
return sorted_s1 == sorted_s2;
}
std::vector<std::string> removeAnagrams(std::vector<std::string>& words) {
if (words.empty()) return {};
std::vector<std::string> result;
result.push_back(words[0]);
for (size_t i = 1; i < words.size(); ++i) {
if (!areAnagrams(result.back(), words[i])) {
result.push_back(words[i]);
}
}
return result;
}
int main() {
std::vector<std::string> words = {"abba", "baba", "bbaa", "cd", "cd"};
std::vector<std::string> result = removeAnagrams(words);
std::cout << "Resultant words:";
for (const auto& word : result) {
std::cout << " " << word;
}
std::cout << std::endl;
return 0;
}
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?