MediumNo. 0249LeetCode Premium

Group Shifted Strings — LeetCode 249 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
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

PythonSolution
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

Time
O(L)
Space · auxiliary
O(L)where L is the sum of the lengths of all strings

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

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy
0522Longest Uncommon Subsequence IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.