0 votes
in Snowflake by
What is the best way to remove a string that is an anagram of an earlier string from an array?

1 Answer

0 votes
by
For instance, an array of strings arr is given. The task is to remove all strings that are anagrams of an earlier string, then print the remaining array in sorted order.

Examples:  

Input: arr[] = { “Scaler”, “Lacers”, “Accdemy”, “Academy” }, N = 4

Output: [“Scaler”, “Academy”,]  

Explanation: “Listen” and “Silent” are anagrams, so we remove “Silent”. Similarly, “Scaler” and “Lacers” are anagrams, so we remove “Lacers”.

 

Code Implementation

import java.util.*;

class InterviewBit{

// Function to remove the anagram String

static void removeAnagrams(String arr[], int N)

{

   // vector to store the final result

    Vector ans = new Vector();

   // A data structure to keep track of previously encountered Strings

   HashSet found = new HashSet ();

   for (int i = 0; i < N; i++) {  

       String word = arr[i];  

       // Sort the characters of the current String

       word = sort(word);

       // Check if the current String is not present in the hashmap

       // Then, push it into the resultant vector and insert it into 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[]= { "Scaler", "Lacers", "Accdemy", "Academy" };

   int N = 4;

   removeAnagrams(arr, N);

  }

}

Output:

Scaler Academy
...