Unique Substrings in Wraparound String

MediumDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Let base be the infinite string "...zabcdefghijklmnopqrstuvwxyzabcd...", i.e. the lowercase alphabet repeated forever so that a follows z. Given a string s, return how many **distinct non-empty** substrings of s also appear as substrings of base. Equivalently, count the distinct substrings of s in which every character is the alphabetical successor of the previous one, with z followed by a.

Examples

Input: s = "a"
Output: 1
Only `"a"`.
Input: s = "cac"
Output: 2
`"a"` and `"c"`; `"ca"` and `"ac"` are not consecutive letters.
Input: s = "zab"
Output: 6
`"z"`, `"a"`, `"b"`, `"za"`, `"ab"`, `"zab"`.

Constraints

  • 1 <= s.length <= 10^5
  • `s` consists of lowercase English letters
  • Substrings are counted once no matter how often they occur

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems