Unique Substrings in Wraparound String - 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 that are present in base.

A substring is a contiguous sequence of characters within a string. For example, "abc" is a substring of "abcde" but "aec" is not.

Input & Output

Example 1 — Basic Consecutive Sequence
$ Input: s = "abc"
Output: 6
💡 Note: Substrings are: "a", "b", "c", "ab", "bc", "abc". All are consecutive in wraparound string, so answer is 6.
Example 2 — Wraparound Case
$ Input: s = "zabc"
Output: 10
💡 Note: Includes wraparound: "z" → "a". Valid substrings: "z", "a", "b", "c", "za", "ab", "bc", "zab", "abc", "zabc". Total: 10.
Example 3 — Duplicate Characters
$ Input: s = "cac"
Output: 2
💡 Note: Valid substrings are "c" and "a". Even though "c" appears twice, we only count unique substrings.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters.

Visualization

Tap to expand
Unique Substrings in Wraparound StringBase: ...xyzabcdefghijklmnopqrstuvwxyzabc...abcInput: s = "abc"Valid SubstringsLength 1: "a", "b", "c"Length 2: "ab", "bc"Length 3: "abc"All consecutive in wraparound alphabet ✓Output: 6 unique substrings
Understanding the Visualization
1
Input String
Given string s with lowercase letters
2
Find Valid Sequences
Identify consecutive sequences in wraparound alphabet
3
Count Unique Substrings
Sum all possible unique substrings from valid sequences
Key Takeaway
🎯 Key Insight: For each letter, track the maximum length of consecutive sequence ending at that letter, then sum all lengths
Asked in
Google 25 Facebook 20 Amazon 15
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