Skip to main content

Find Resultant Array After Removing Anagrams - Solution & Explanation

EasyArrayHash TableStringSorting21 min readAsked at: Amazon, Microsoft, IBM +4
Practice this problem

Problem Statement

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 performing this operation as long as you can select an index that satisfies the conditions.

Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc".

 

Example 1:

Input: words = ["abba","baba","bbaa","cd","cd"]
Output: ["abba","cd"]
Explanation:
One of the ways we can obtain the resultant array is by using the following operations:
- Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2].
  Now words = ["abba","baba","cd","cd"].
- Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1].
  Now words = ["abba","cd","cd"].
- Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2].
  Now words = ["abba","cd"].
We can no longer perform any operations, so ["abba","cd"] is the final answer.

Example 2:

Input: words = ["a","b","c","d","e"]
Output: ["a","b","c","d","e"]
Explanation:
No two adjacent strings in words are anagrams of each other, so no operations are performed.

 

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.

Approach Overview

Problem Overview: You are given an array of words. If two adjacent words are anagrams, remove the later one. Continue scanning left to right and keep only the first occurrence in each consecutive anagram group. The final result is the array of remaining words after these removals.

Approach 1: Sort and Compare (Time: O(n * k log k), Space: O(k))

The most common strategy is to normalize each word so all anagrams share the same representation. Sort the characters of every word using sort(). Two strings are anagrams if their sorted forms are identical. Iterate through the array once, compute the sorted version of the current word, and compare it with the sorted version of the previously accepted word. If they match, skip the current word; otherwise append it to the result array. Sorting each string costs O(k log k) where k is the word length, and you perform this for n words, resulting in O(n * k log k) time. Space usage stays O(k) for the temporary sorted representation. This approach is simple, reliable, and commonly used for string anagram detection problems.

Approach 2: Frequency Count and Compare (Time: O(n * k), Space: O(26))

A more efficient approach avoids sorting entirely. Instead, build a frequency vector for each word representing counts of characters a–z. Two words are anagrams if their frequency arrays match exactly. While iterating through the input, compute the frequency array for the current word and compare it with the frequency array of the last accepted word. If the arrays are identical, the current word is an anagram of the previous one and should be skipped. Otherwise add it to the result and update the stored frequency array. Counting characters requires O(k) time per word, so the full traversal runs in O(n * k). Space complexity remains O(26) (constant) for the frequency vector. This technique is common in problems involving hash tables or character counting and avoids the overhead of sorting.

Both approaches rely on the same insight: you only compare the current word with the previously kept word, not with the entire result array. The constraint that removals happen only for adjacent anagrams simplifies the logic to a single linear pass over the array.

Recommended for interviews: The frequency-count solution is usually preferred because it improves the complexity from O(n * k log k) to O(n * k). Still, explaining the sorting approach first demonstrates understanding of the classic sorting-based anagram check. Transitioning to frequency counting shows optimization and stronger algorithmic thinking.

Approach 1: Sort and Compare

This approach involves sorting each word in the array and comparing adjacent sorted words. If two adjacent sorted words are equal, they are anagrams and we remove the second word. Iterate through the array, adjusting the index when necessary due to removals.

This C solution defines a function that checks if two words are anagrams by sorting their characters and comparing the results. We iterate through the words array and remove adjacent anagrams. Sorting is performed with qsort, and each comparison's result dictates if we should remove a word.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * m log m) where n is the number of words and m is the maximum length of a word, due to sorting each word.
Space Complexity: O(m) for each duplicated word during comparisons.

Try this approach in the editor →

Approach 2: Frequency Count and Compare

This method involves counting the frequency of each letter for the words being compared. Adjacency checks then use these frequency dictionaries (or arrays) to decide if words are anagram pairs, which leads to the removal of one.

The C solution uses a fixed-size array to count character occurrences. It removes anagrams by verifying that each letter frequency cancels out.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * m) where n is number of words and m is length of longest word.
Space Complexity: O(1) due to constant space usage for the frequency arrays.

Try this approach in the editor →

Approach 3: Simulation

We first add words[0] to the answer array, then traverse from words[1]. If words[i - 1] and words[i] are not anagrams, we add words[i] to the answer array.

The problem is converted to determining whether two strings are anagrams. We define a helper function check(s, t) to achieve this. If s and t are not anagrams, we return true; otherwise, we return false.

In the function check(s, t), we first check if the lengths of s and t are equal. If they are not, we return true. Otherwise, we use an array cnt of length 26 to count the occurrences of each character in s, then traverse each character in t and decrement cnt[c] by 1. If cnt[c] is less than 0, we return true. If we traverse all characters in t without issues, it means s and t are anagrams, and we return false.

The time complexity is O(L), and the space complexity is O(|\Sigma|). Here, L is the length of the array words, and \Sigma is the character set, which is lowercase English letters, so |\Sigma| = 26.

Code

Python

Java

C++

Go

TypeScript

Rust

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Sort and Compare

Time Complexity: O(n * m log m) where n is the number of words and m is the maximum length of a word, due to sorting each word.
Space Complexity: O(m) for each duplicated word during comparisons.

Frequency Count and Compare

Time Complexity: O(n * m) where n is number of words and m is length of longest word.
Space Complexity: O(1) due to constant space usage for the frequency arrays.

Simulation—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sort and CompareO(n * k log k)O(k)Simple implementation and common approach when checking anagrams with sorting
Frequency Count and CompareO(n * k)O(26)Optimal solution when words contain lowercase letters and sorting overhead should be avoided

Video Solution

Find Resultant Array After Removing Anagrams | Multiple Approach | Leetcode 2273 | codestorywithMIK • codestorywithMIK • 4,982 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Find Resultant Array After Removing Anagrams easy or hard?
The problem is classified as Easy on LeetCode with an acceptance rate around 70%. The challenge mainly involves recognizing that only adjacent words need to be checked and applying a standard anagram detection technique.
Find Resultant Array After Removing Anagrams Python/Java solution
In Python or Java, iterate through the words and compute either the sorted version of the string or a frequency array of characters. Compare it with the previous stored representation. If they match, skip the word; otherwise add it to the result list.
How to solve Find Resultant Array After Removing Anagrams in O(n)?
Strict O(n) is not possible because each word must be inspected character by character. The closest optimal solution is O(n * k) using a character frequency array. For each word, compute a 26-element count and compare it with the previous word's count to detect anagrams.
What is the best approach for Find Resultant Array After Removing Anagrams?
The frequency count approach is typically the best solution. Build a 26-length character frequency array for each word and compare it with the previous word's frequency array. This avoids sorting and runs in O(n * k) time where n is the number of words and k is the word length.
Is Find Resultant Array After Removing Anagrams asked at Google/Amazon/Meta?
Anagram detection and string normalization problems frequently appear in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary, the underlying techniques such as sorting strings or using character frequency arrays are commonly tested.
What data structure is used in Find Resultant Array After Removing Anagrams?
The solution primarily uses arrays and character frequency counters. A fixed-size array of length 26 is commonly used to track letter counts. Some implementations also rely on sorting utilities and simple array traversal.
What is the time complexity of Find Resultant Array After Removing Anagrams?
The sorting approach runs in O(n * k log k) because each word must be sorted before comparison. The optimized frequency counting approach reduces this to O(n * k) by counting characters instead of sorting them. Space complexity is O(k) for sorting or O(26) for the frequency array.

Ready to solve this problem?

Practice Find Resultant Array After Removing Anagrams with our built-in code editor and test cases.

Practice on FleetCode