Skip to main content

Command Palette

Search for a command to run...

Find Resultant Array After Removing Anagrams

Published
2 min read
Find Resultant Array After Removing Anagrams
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

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".

LeetCode Problem - 2273

import java.util.*;

class Solution {
    public List<String> removeAnagrams(String[] words) {
        List<String> result = new ArrayList<>(Arrays.asList(words));

        int i = 1; // Start from the second element
        while (i < result.size()) {
            String curr = result.get(i);
            String prev = result.get(i - 1);

            if (checkAnagram(curr, prev)) {
                result.remove(i); // Remove the anagram
            } else {
                i++; // Only increment i if no anagram was removed
            }
        }

        return result;
    }

    public boolean checkAnagram(String str1, String str2) {
        // Convert both strings to character arrays and sort them
        char[] chArr1 = str1.toCharArray();
        char[] chArr2 = str2.toCharArray();

        Arrays.sort(chArr1);
        Arrays.sort(chArr2);

        // Check if sorted arrays are equal
        return Arrays.equals(chArr1, chArr2);
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.