There is a stream of words which contains Anagrams. How would you print anagrams in a single bucket from that stream?

By | June 18, 2020

Hello Friends,

In this post we will talk and learn about one of the  very important java programming interview question  let’s say  There is a stream of words which contains Anagrams. How would you print anagrams in a single bucket from that stream?

Below Algorithm and data stricture we will use to implement same:

1) Use a hashmap with string as key and list<string> as value where list of strings contain all anagrams of a given key string.
2) For each word in the input array, create a key by sorting the word and put this word to that list whose key is the sorted word.
for example [aakk -> akka, akak] If it does not exist then create a new list with the sorted word as key in map.
3) Print all strings from the list whose key is the input word(sorted string).

Output of Above program: 

[xyyx, xyxy]
[caac, caca, ccaa]

Time Complexity:If we ignore the time consumed by sorting an individual string then we can say that the above approach takes Big O(n) time complexity. Otherwise the actual time complexity would be N log N (sorting) + N (compare)

You may also like:

Difference between List and Set in Java Collection ?
When should we choose LinkedList over ArrayList for a given Scenario and Why?
Is there concurrent version for TreeMap and TreeSet in Java Collections Framework?
What is difference between Collections. Sort() and Arrays.sort()? Which one is better with respect to time efficiency?
What are fail-fast and fail-safe Iterator?
What is difference between Iterator and LisIterator?
Why Prime Numbers are considered in writing certain algorithms like hashcode()?

That’s all about How would you print anagrams in a single bucket from that stream?
If you have any feedback or suggestion please feel free to drop in blow comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *