Written by
Amit Bansal
on
on
LeetCode Problem: 49. Group Anagrams
Problem description can be found here
So in this problem we need to group all the anagrams together.
Here is a scala solution:
In this solution we are recursively traversing over all the strings and appending it to the value in a map. Where key is string sorted version of the same string.
So after after the method call to solve
.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
We will have a map that looks like this.
Now all we need to do is extract only values for all keys.
which can be done using this .values.toList
So here is our solution.
With some clever use of Scala api we can also do something like this:
So apparently in the previous solution we are implementing a version of groupBy
method.