Group Shifted Strings — LeetCode 249 Python Solution

MediumLeetCode PremiumArrayHash TableString
Problem
#249
Pattern
Hash Map
Reading time
2 min

The problem

Perform the following shift operations on a string: Right shift: Replace every letter with the successive letter of the English alphabet, where 'z' is replaced by 'a'. For example, "abc" can be right-shifted to "bcd" or "xyz" can be right-shifted to "yza".

Python solution

Python
class Solution:
    def groupStrings(self, strings: List[str]) -> List[List[str]]:
        g = defaultdict(list)
        for s in strings:
            diff = ord(s[0]) - ord("a")
            t = []
            for c in s:
                c = ord(c) - diff
                if c < ord("a"):
                    c += 26
                t.append(chr(c))
            g["".join(t)].append(s)
        return list(g.values())

Complexity

MeasureComplexity
TimeO(L)
SpaceO(L), where L is the sum of the lengths of all strings auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 249. Group Shifted Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 249. Group Shifted Strings?
LeetCode 249. Group Shifted Strings is rated Medium on LeetCode.
What is the time complexity of LeetCode 249. Group Shifted Strings?
The Python solution on this page runs in O(L).
What is the space complexity of LeetCode 249. Group Shifted Strings?
The Python solution on this page uses O(L), where L is the sum of the lengths of all strings auxiliary space.
What topics does LeetCode 249. Group Shifted Strings cover?
LeetCode 249. Group Shifted Strings is tagged Array, Hash Table and String on LeetCode.
Is LeetCode 249. Group Shifted Strings a premium problem?
Yes. LeetCode 249. Group Shifted Strings is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview