Removing string that is an anagram of an earlier string
Last Updated :
22 Aug, 2022
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:
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 HashSet.
Follow the below steps to implement the idea:
- Create an auxiliary array to keep the resultant strings, and HashSet to keep a track of the string that we have found so far.
- Then iterate through the given string of array, sort the current string and check if the string is present in the HashSet.
- If the current string is not found in the HashSet, then push arr[i] in the resultant array, and insert the sorted string in the HashSet.
- Finally, sort the resultant array and print each string.
Below is the implementation of the above approach.
C++
// 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 occurred 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;
}
Java
// 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 occurred 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
Python3
# 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 occurred 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
C#
// 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 occurred 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
JavaScript
<script>
// Javascript implementation to remove
// all the anagram Strings
// Function to remove the anagram String
function removeAnagrams(arr, N)
{
// Vector to store the final result
let ans = [];
// Data structure to keep a mark
// of the previously occurred String
let found = new Set();
for(let i = 0; i < N; i++)
{
let 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.has(word))
{
ans.push(arr[i]);
found.add(word);
}
}
// Sort the resultant vector of Strings
(ans).sort();
// Print the required array
for(let i = 0; i < ans.length; ++i)
{
document.write(ans[i] + " ");
}
}
function sort(inputString)
{
// Convert input string to char array
let tempArray = inputString.split("");
// Sort tempArray
(tempArray).sort();
// Return new sorted string
return (tempArray).join("");
}
// Driver code
let arr = [ "geeks", "keegs",
"code", "doce" ];
let N = 4;
removeAnagrams(arr, N);
// This code is contributed by unknown2108
</script>
Time Complexity: O(N * (M log M)) where N is the size of the array and m is the length of the word.
Auxiliary space: O(N).
Please suggest if someone has a better solution that is more efficient in terms of space and time.
Similar Reads
Find all substrings that are anagrams of another substring of the string S Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at a different index. Examples: Input: S = "aba"Output: a a ab baExplanation:Following substrings are anagra
6 min read
Convert string X to an anagram of string Y with minimum replacements Given two strings X and Y, we need to convert string X into an anagram of string Y with minimum replacements. If we have multiple ways of achieving the target, we go for the lexicographically smaller string where the length of each string \in [1, 100000] Examples: Input : X = "CDBABC" Y = "ADCABD" O
13 min read
Remove minimum characters so that two strings become anagram Given two strings in lowercase, the task is to make them anagrams. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagrams of each other if one of them can be converted
12 min read
Remove all occurrences of a string t in string s using Boyer-Moore Algorithm Given a string s and string t, the task is to remove all occurrences of a string t in a string s using the Boyer-Moore algorithm. Examples: Input: s = "ababaababa", t = "aba" Output: baab Input: s = "Geeksforgeeks", t = "eek"Output: Gsforgs Approach: This can be solved with the following idea: We in
10 min read
Program for removing i-th character from a string Given a string S along with an integer i. Then your task is to remove ith character from S. Examples: Input: S = Hello World!, i = 7Output: Hello orld!Explanation: The Xth character is W and after removing it S becomes Hello orld! Input: S = GFG, i = 1Output: GGExplanation: It can be verified that a
5 min read