Unique substrings in circular string in JavaScript

In JavaScript, we need to find the number of unique non-empty substrings of a given string that exist in an infinite wraparound string of the alphabet. The wraparound string is an infinite repetition of "abcdefghijklmnopqrstuvwxyz".

Problem Statement

Given a string S, which is an infinite wraparound string of:

"abcdefghijklmnopqrstuvwxyz"

The infinite string S looks like:

"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."

We need to find how many unique non-empty substrings of a given input string are present in this infinite wraparound string.

Example

For input string "zab":

Input: "zab"
Output: 6

The six valid substrings are: "z", "a", "b", "za", "ab", "zab"

Algorithm Explanation

The key insight is that a substring is valid if it forms a consecutive sequence in the circular alphabet. We use dynamic programming to track the maximum length of valid substrings ending with each character.

  • Use an array dp[26] to store the maximum length of valid substring ending with each letter

  • Check if consecutive characters form a valid sequence (either next letter or wraps from 'z' to 'a')

  • Sum all values in dp array to get total unique substrings

Solution

const str = "zab";

const allSubstrings = (str = '') => {
    if (!str.length) return 0;
    
    // dp[i] stores max length of valid substring ending with character i
    const dp = new Array(26).fill(0);
    dp[str.charCodeAt(0) - 97] = 1;
    let maxCount = 1;
    
    for (let i = 1; i  sum + count, 0);
};

console.log(allSubstrings(str));
6

How It Works

For string "zab":

  1. Initialize dp array and set dp[25] = 1 for 'z'

  2. Process 'a': 'z' ? 'a' is valid (wraps around), maxCount = 2, dp[0] = 2

  3. Process 'b': 'a' ? 'b' is valid (consecutive), maxCount = 3, dp[1] = 3

  4. Final dp: [2, 3, 0, 0, ..., 0, 1] (indices 0='a', 1='b', 25='z')

  5. Sum: 2 + 3 + 1 = 6 unique substrings

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of input string

  • Space Complexity: O(1) as we use fixed size array of 26 elements

Conclusion

This solution efficiently counts unique substrings in a circular alphabet string using dynamic programming. The key is recognizing that we only need to track the maximum valid substring length ending with each character.

Updated on: 2026-03-15T23:19:00+05:30

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements