Leetcode #467: Unique Substrings in Wraparound String
In this guide, we solve Leetcode #467 Unique Substrings in Wraparound String in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
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
The time complexity is , where is the length of the string . The space complexity is , where is the character set, in this case, the set of lowercase letters.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.