Interview Questions/Coding/Adjacent Anagram Cleanup

Adjacent Anagram Cleanup

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Adjacent Anagram Cleanup

A log compressor processes words from left to right. A new word is discarded if it is an anagram of the most recent word that survived compression. Only adjacent surviving words matter. If a word is removed, the next word is compared against the last word that remains in the compressed list, not against the removed word. The original casing and spelling of kept words must be preserved. Input Format: You are given an array words. Output Format: Return the final word list after adjacent anagram cleanup.

Examples

Example 1
Input:
words = ["abba", "baba", "bbaa", "cd", "cd"]
Output:
abba cd

Explanation: The kept words are ["abba", "cd"]. Removed adjacent anagrams: ["baba", "bbaa", "cd"]. Printing them in order gives abba cd.

Approach hint

Look for the state that actually matters after each operation.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp