Problem 467 · LeetCode 467(opens in a new tab)
Unique Substrings in Wraparound String
MediumDynamic programming
Picture the alphabet written out forever in a loop: ...xyzabcdef...xyzabc..., where a comes right after z. Call that endless string the wraparound string.
You are given a string s. Count the different non-empty substrings of s that also appear somewhere in the wraparound string. A substring that shows up in several places in s counts once.
Example 1
Input: s = "cdecd" Output: 6 Why: c, d, e, cd, de, cde; the second "cd" is a repeat
2 more examples and the constraints
Example 2
Input: s = "yzab" Output: 10 Why: the whole string is one run, z then a, giving 4+3+2+1
Example 3
Input: s = "xyx" Output: 3 Why: x, y and xy; "yx" goes backwards
Constraints
- 1 ≤ length of s ≤ 100,000
- s holds only lowercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Collect substrings in a setO(n²)
- Longest run per ending letterO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Work for one 100,000-letter run | Verdict |
|---|---|---|---|
| Collect substrings in a set | O(n²) | Times out on long runs | |
| Longest run per ending letter | O(n) | Best; one pass |
n = length of s.
Edge cases to test
- The wrap from z to a.
zais valid. Compare letters with(b − a) mod 26 == 1, notb − a == 1. - Repeated runs.
abcabchas the runabctwice. Taking the max, not the sum, counts it once: the answer is 6. - A short run inside a longer one. In
bcabcd, the runbcis covered byabcd, which also ends its ownbc. The max keeps only the longer run. - Runs longer than 26. A run can lap the alphabet. Each length is still a different substring, so best values can go past 26.
Common mistakes
- Adding the run length to the total at every step, which counts repeated substrings more than once.
- Forgetting the wrap, so
zabreaks the run. - Returning the longest run, or the sum over runs, instead of the sum of the 26 per-letter maxima.
How to talk through it
- 1Clarify. Distinct substrings only? Does
afollowz? How long can s be? - 2Start simple. Extend every start while the letters chain, and put the substrings in a set. Correct, but quadratic.
- 3Spot the structure. Once you know the last letter and the length, the valid substring is decided. So the longest run ending in a letter counts them all.
- 4Code the pass. Track the current run length and keep the max per letter; the answer is the sum of 26 numbers.
- 5Test out loud. Walk through
cdecdandyzab, and check that a repeated run is not counted twice.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?