Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created October 13, 2025 17:13
Show Gist options
  • Select an option

  • Save tatsuyax25/7fee0798a2e1e68662a270c9c725d68f to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/7fee0798a2e1e68662a270c9c725d68f to your computer and use it in GitHub Desktop.
You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep
/**
* @param {string[]} words
* @return {string[]}
*/
var removeAnagrams = function(words) {
// Helper function to check if two words are anagrams
const isAnagram = (word1, word2) => {
// Sort the letters of both words and compare
return word1.split('').sort().join('') === word2.split('').sort().join('');
};
// Initialize a result array with the first word (it can't be removed)
const result = [words[0]];
// Start from the second word and compare with the last word in result
for (let i = 1; i < words.length; i++) {
const prev = result[result.length - 1];
const curr = words[i];
// Only add current word if it's NOT an anagram of the previous one
if (!isAnagram(prev, curr)) {
result.push(curr);
}
// If it IS an anagram, we skip it (i.e., don't add to result)
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment