Unique Substrings in Wraparound String — LeetCode 467 Python Solution

MediumStringDynamic Programming
Problem
#467
Reading time
2 min

The problem

We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so base will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Given a string s, return the number of unique non-empty substrings of s are present in base.

Example

Input
s = "a"
Output
1
Explanation
Only the substring "a" of s is in base.

Python solution

Python
class Solution:
    def findSubstringInWraproundString(self, s: str) -> int:
        f = defaultdict(int)
        k = 0
        for i, c in enumerate(s):
            if i and (ord(c) - ord(s[i - 1])) % 26 == 1:
                k += 1
            else:
                k = 1
            f[c] = max(f[c], k)
        return sum(f.values())

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(|\Sigma|), where \Sigma is the character set, in this case, the set of lowercase letters auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 467. Unique Substrings in Wraparound String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 467. Unique Substrings in Wraparound String?
LeetCode 467. Unique Substrings in Wraparound String is rated Medium on LeetCode.
What is the time complexity of LeetCode 467. Unique Substrings in Wraparound String?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 467. Unique Substrings in Wraparound String?
The Python solution on this page uses O(|\Sigma|), where \Sigma is the character set, in this case, the set of lowercase letters auxiliary space.
What topics does LeetCode 467. Unique Substrings in Wraparound String cover?
LeetCode 467. Unique Substrings in Wraparound String is tagged String and Dynamic Programming on LeetCode.

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