Unique Substrings in Wraparound String - Problem

Imagine an infinite wraparound string containing the alphabet repeated endlessly:

"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd..."

This magical string has a special property: it wraps around from 'z' back to 'a', creating an endless cycle of alphabetical characters.

Given a string s, your task is to determine how many unique non-empty substrings of s can be found within this infinite wraparound string.

Key Points:

  • A substring is valid if it appears consecutively in the wraparound pattern
  • Characters must be in alphabetical order (with 'z' followed by 'a')
  • We only count unique substrings - duplicates don't add to the count
  • Examples of valid sequences: "abc", "xyz", "zabc", "xyza"

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "a"
โ€บ Output: 1
๐Ÿ’ก Note: Only one substring "a" exists, and it's present in the wraparound string.
example_2.py โ€” Sequential Characters
$ Input: s = "caba"
โ€บ Output: 6
๐Ÿ’ก Note: Valid substrings are: "c", "a", "b", "a", "ca", "ab". Note that "a" appears twice but we only count unique substrings, so the unique ones are: "c", "a", "b", "ca", "ab", "aba" = 6 total.
example_3.py โ€” Wraparound Case
$ Input: s = "zabc"
โ€บ Output: 10
๐Ÿ’ก Note: All substrings are valid: "z", "a", "b", "c", "za", "ab", "bc", "zab", "abc", "zabc". The sequence wraps from 'z' to 'a' correctly.

Visualization

Tap to expand
Circular Alphabet VisualizationabcdzValid path: aโ†’bโ†’c (3 unique substrings ending at c)
Understanding the Visualization
1
Walk the Track
Move through the string, extending your path when possible
2
Mark Positions
At each letter, record the longest valid sequence ending there
3
Count Paths
Sum all maximum lengths - this gives total unique substrings
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating substrings, track the maximum valid sequence length ending at each character - this automatically counts all unique substrings without duplicates!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the input string

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only need array of size 26 for alphabet characters

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters only
  • Time limit: 1 second per test case
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen