Showing posts with label Group Shifted Strings - Python Solution Leetcode. Show all posts
Showing posts with label Group Shifted Strings - Python Solution Leetcode. Show all posts

Group Shifted Strings - Python Solution Leetcode

 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:

"abc" -> "bcd" -> ... -> "xyz"

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

Example:

Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output: 
[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]
class Solution:
    def groupStrings(self, strings: List[str]) -> List[List[str]]:
        groups = collections.defaultdict(list)
        for s in strings:
            key = ()
            for i in range(len(s)-1):
                key += ((26+ ord(s[i+1]) - ord(s[i])) % 26,)
            groups[key] = groups.get(key,[])+[s]

        return groups.values()
                         
TC:O(no of strings * longest string length) SC: O(n) Hashmap storage.

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...