Skip to content
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.

Try it on LeetCode(opens in a new tab)
  1. Collect substrings in a setO(n²)
  2. Longest run per ending letterO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeWork for one 100,000-letter runVerdict
Collect substrings in a setO(n²)
Times out on long runs
Longest run per ending letterO(n)
Best; one pass

n = length of s.

Edge cases to test

  • The wrap from z to a. za is valid. Compare letters with (b − a) mod 26 == 1, not b − a == 1.
  • Repeated runs. abcabc has the run abc twice. Taking the max, not the sum, counts it once: the answer is 6.
  • A short run inside a longer one. In bcabcd, the run bc is covered by abcd, which also ends its own bc. 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 za breaks 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

  1. 1Clarify. Distinct substrings only? Does a follow z? How long can s be?
  2. 2Start simple. Extend every start while the letters chain, and put the substrings in a set. Correct, but quadratic.
  3. 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.
  4. 4Code the pass. Track the current run length and keep the max per letter; the answer is the sum of 26 numbers.
  5. 5Test out loud. Walk through cdecd and yzab, 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?