Unique Substrings in Wraparound String — LeetCode 467 Python Solution
- Problem
- #467
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(|\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.