Removing string that is an anagram of an earlier string

Given an array arr of strings, the task is to remove the strings that are an anagram of an earlier string, then print the remaining array in sorted order.

Examples:

Input: arr[] = { “geeks”, “keegs”, “code”, “doce” }, N = 4
Output: [“code”, “geeks”]
Explanation:
“geeks” and “keegs” are anagrams, so we remove “keegs”.
Similarly, “code” and “doce” are anagrams, so we remove “doce”.

Input : arr[] = {“tea”, “ate”, “anagram”, “eat”, “gramaan”}, N = 5
Output : [“anagram”, “tea”]
Explanation: “ate” and “eat” are anagram of “tea”.
“gramaan” is an anagram of “anagram” hence, array becomes [“anagram”, “tea”].

Approach:



Approach: In order to check whether the given two strings are anagrams are not, we can simply sort both the strings and compare them. Also, to check if a string has occurred or not, we can use a hashmap.

  1. Create an auxiliary array to keep the resultant strings, and a hashmap to keep a mark of the string that we have found so far.
  2. Then iterate through the given string of array, sort the current string and check that string in the hashmap.
  3. If the current string is not found in the hashmap, then push arr[i] in the resultant array, and insert the sorted string in hashmap.
  4. Finally, sort the resultant array and print each string.

Below is the implementation of above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to remove
// all the anagram strings
#include <bits/stdc++.h>
using namespace std;
  
// Function to remove the anagram string
void removeAnagrams(string arr[], int N)
{
    // vector to store the final result
    vector<string> ans;
  
    // data structure to keep a mark
    // of the previously occured string
    unordered_set<string> found;
  
    for (int i = 0; i < N; i++) {
  
        string word = arr[i];
  
        // Sort the characters
        // of the current string
        sort(begin(word), end(word));
  
        // Check if current string is not
        // present inside the hashmap
        // Then push it in the resultant vector
        // and insert it in the hashmap
        if (found.find(word) == found.end()) {
  
            ans.push_back(arr[i]);
            found.insert(word);
        }
    }
  
    // Sort the resultant vector of strings
    sort(begin(ans), end(ans));
  
    // Print the required array
    for (int i = 0; i < ans.size(); ++i) {
        cout << ans[i] << " ";
    }
}
  
// Driver code
int main()
{
    string arr[]
        = { "geeks", "keegs",
            "code", "doce" };
    int N = 4;
  
    removeAnagrams(arr, N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to remove
// all the anagram Strings
import java.util.*;
  
class GFG{
   
// Function to remove the anagram String
static void removeAnagrams(String arr[], int N)
{
    // vector to store the final result
    Vector<String> ans = new Vector<String>();
   
    // data structure to keep a mark
    // of the previously occured String
    HashSet<String> found = new HashSet<String> ();
   
    for (int i = 0; i < N; i++) {
   
        String word = arr[i];
   
        // Sort the characters
        // of the current String
        word = sort(word);
   
        // Check if current String is not
        // present inside the hashmap
        // Then push it in the resultant vector
        // and insert it in the hashmap
        if (!found.contains(word)) {
   
            ans.add(arr[i]);
            found.add(word);
        }
    }
   
    // Sort the resultant vector of Strings
    Collections.sort(ans);
   
    // Print the required array
    for (int i = 0; i < ans.size(); ++i) {
        System.out.print(ans.get(i)+ " ");
    }
}
static String sort(String inputString) 
    // convert input string to char array 
    char tempArray[] = inputString.toCharArray(); 
        
    // sort tempArray 
    Arrays.sort(tempArray); 
        
    // return new sorted string 
    return new String(tempArray); 
}
    
// Driver code
public static void main(String[] args)
{
    String arr[]
        = { "geeks", "keegs",
            "code", "doce" };
    int N = 4;
   
    removeAnagrams(arr, N);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to remove
# all the anagram strings
  
# Function to remove the anagram string
def removeAnagrams(arr, N):
  
    # vector to store the final result
    ans = []
  
    # data structure to keep a mark
    # of the previously occured string
    found = dict()
  
    for i in range(N):
  
        word = arr[i]
  
        # Sort the characters
        # of the current string
        word = " ".join(sorted(word))
  
        # Check if current is not
        # present inside the hashmap
        # Then push it in the resultant vector
        # and insert it in the hashmap
        if (word not in found):
  
            ans.append(arr[i])
            found[word] = 1
  
    # Sort the resultant vector of strings
    ans = sorted(ans)
  
    # Print the required array
    for i in range(len(ans)):
        print(ans[i], end=" ")
  
# Driver code
if __name__ == '__main__':
    arr=["geeks", "keegs","code", "doce"]
    N = 4
  
    removeAnagrams(arr, N)
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to remove
// all the anagram Strings
using System;
using System.Collections.Generic;
  
class GFG{
    
// Function to remove the anagram String
static void removeAnagrams(String []arr, int N)
{
    // vector to store the readonly result
    List<String> ans = new List<String>();
    
    // data structure to keep a mark
    // of the previously occured String
    HashSet<String> found = new HashSet<String> ();
    
    for (int i = 0; i < N; i++) {
    
        String word = arr[i];
    
        // Sort the characters
        // of the current String
        word = sort(word);
    
        // Check if current String is not
        // present inside the hashmap
        // Then push it in the resultant vector
        // and insert it in the hashmap
        if (!found.Contains(word)) {
    
            ans.Add(arr[i]);
            found.Add(word);
        }
    }
    
    // Sort the resultant vector of Strings
    ans.Sort();
    
    // Print the required array
    for (int i = 0; i < ans.Count; ++i) {
        Console.Write(ans[i]+ " ");
    }
}
static String sort(String inputString) 
    // convert input string to char array 
    char []tempArray = inputString.ToCharArray(); 
         
    // sort tempArray 
    Array.Sort(tempArray); 
         
    // return new sorted string 
    return String.Join("",tempArray); 
}
     
// Driver code
public static void Main(String[] args)
{
    String []arr
        = { "geeks", "keegs",
            "code", "doce" };
    int N = 4;
    
    removeAnagrams(arr, N);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

code geeks

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.