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 String INPUT Base string (infinite wraparound): ...xyz a b c d e f ... ... ... x y z a b Input string s: "abc" a b c idx: 0 idx: 1 idx: 2 ALGORITHM STEPS 1 Track max length ending at each char (a-z) 2 Check consecutive curr = prev+1 or z-->a wrap 3 Update max[char] Store longest valid substring 4 Sum all max values Total unique substrings Processing "abc" char len max[char] substrings a 1 max[a]=1 "a" b 2 max[b]=2 "b","ab" c 3 max[c]=3 "c","bc","abc" Sum = 1 + 2 + 3 = 6 FINAL RESULT All 6 unique substrings: "a" "b" "c" "ab" "bc" "abc" Length distribution: len=1 3 len=2 2 len=3 1 Output: 6 OK - All substrings valid! Key Insight: Track the maximum length of consecutive substring ending at each character (a-z). For each ending char, max length = count of unique substrings ending there. Sum all 26 values. Time: O(n) | Space: O(1) - only 26 character counts needed TutorialsPoint - Unique Substrings in Wraparound String | Optimal Solution
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