Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created October 13, 2025 22:42
Show Gist options
  • Select an option

  • Save Ifihan/7ddf545240e79f0b264ad64dd5ba2a59 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/7ddf545240e79f0b264ad64dd5ba2a59 to your computer and use it in GitHub Desktop.
Find Resultant Array After Removing Anagrams

Question

Approach

I scan the list and keep a result stack. For each word, I compare its sorted characters to the sorted characters of the last word kept. If they are anagrams (sorted equal), I skip the current word (simulate deleting it). Otherwise I append it to the stack. At the end the stack is the final array after all deletions. This works because deletions only depend on the most recent kept word and the process is order-independent.

Implementation

class Solution:
    def removeAnagrams(self, words: List[str]) -> List[str]:
        res = []
        for w in words:
            if res and sorted(res[-1]) == sorted(w):
                continue
            res.append(w)
        return res

Complexities

  • Time: O(n⋅LlogL), where 𝑛 is number of words and L is max word length (sorting each word).
  • Space: O(n⋅L) for the output and temporary sorted lists.
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment