Leetcode Group Shifted Strings

Tags: ,

Given a string, we can “shift” each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep “shifting” which forms the sequence:

Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.

For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Return:

Note: For the return value, each inner list’s elements must follow the lexicographic order.

A better example:

[“eqdf”, “qcpr”]

((‘q’ – ‘e’) + 26) % 26 = 12, ((‘d’ – ‘q’) + 26) % 26 = 13, ((‘f’ – ‘d’) + 26) % 26 = 2

((‘c’ – ‘q’) + 26) % 26 = 12, ((‘p’ – ‘c’) + 26) % 26 = 13, ((‘r’ – ‘p’) + 26) % 26 = 2

“eqdf”, “qcpr” is a group shifted strings.

We can see a pattern among string of one group, the difference between consecutive characters for all character of string are equal. As in above example take acd, dfg and mop

a c d -> 2 1
d f g -> 2 1
m o p -> 2 1

Since the differences are same, we can use this to identify strings that belong to same group. The idea is to form a string of differences as key. If a string with same difference string is found, then this string also belongs to same group. For example, above three strings have same difference string, that is “21”.

Java Solution: