![]() |
VOOZH | about |
Given an array of strings (all lowercase letters), the task is to group them in such a way that all strings in a group are shifted versions of each other.
Two strings s1 and s2 are called shifted if the following conditions are satisfied:
Examples:
Input: arr[] = ["acd", "dfg", "wyz", "yab", "mop", "bdfh", "a", "x", "moqs"]
Output: [ ["acd", "dfg", "wyz", "yab", "mop"], ["bdfh", "moqs"], ["a", "x"] ]
Explanation: All shifted strings are grouped together.
Input: arr = ["geek", "for", "geeks"]
Output: [["for"], ["geek"], ["geeks"]]
The idea is to generate a unique hash for each group by normalizing the strings. Here normalizing means making the first character of every string equal to 'a' by calculating the required shifts and applying it uniformly to all characters in cyclic fashion.
Example: s = "dca", shifts = 'd' - 'a' = 3
normalized characters: 'd' - 3 = 'a', 'c' - 3 = 'z' and 'a' - 3 = 'x'
normalized string = "azx"The normalized string (hash) represents the shift pattern such that strings with the same pattern have the same hash. We use a hash map to track these hashes, and map them to corresponding groups. For each string, we compute a hash and use it to either create a new group or add the string to an existing group in a single traversal.
acd dfg wyz yab mop bdfh moqs a x
Time Complexity: O(n*k), where n is the length of string array and k is maximum length of a string in string array.
Auxiliary Space: O(n*k), in worst case we might generate n different hash strings respectively for each input string. So we got n different entries in hash map each of length k or less.