KatInterview

467. Unique Substrings in Wraparound String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the number of unique non-empty substrings of a given string s that can be found in the infinite wraparound string of the alphabet, "...zabcdefghijklmnopqrstuvwxyzabcd...". A substring is present in this base string if its characters are alphabetically consecutive, allowing for a wrap from 'z' to 'a'. For example, "cde" and "za" are valid, but "ca" is not.

Solution

Unique Substrings in Wraparound String in Python

class Solution:
    def findSubstringInWraproundString(self, s: str) -> int:
        if not s:
            return 0
        
        # count[i] stores the max length of a valid substring ending with char ('a' + i).
        count = [0] * 26
        
        max_length = 0
        for i in range(len(s)):
            # Check if the current character is consecutive to the previous one.
            # Handles both normal sequence ('b' after 'a') and wrap-around ('a' after 'z').
            if i > 0 and (ord(s[i]) - ord(s[i-1]) == 1 or ord(s[i-1]) - ord(s[i]) == 25):
                max_length += 1
            else:
                # If not consecutive, start a new sequence of length 1.
                max_length = 1
            
            # Update the max length for the substring ending with s[i].
            # A longer valid substring ending with a character 'x' (e.g., "vwx")
            # naturally contains all shorter valid ones ending with 'x' (e.g., "wx", "x").
            # By storing the max length, we count all these implicitly.
            index = ord(s[i]) - ord('a')
            count[index] = max(count[index], max_length)
            
        # The total number of unique substrings is the sum of these maximum lengths.
        return sum(count)

Unique Substrings in Wraparound String in Java

class Solution {
    public int findSubstringInWraproundString(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        // count[i] stores the max length of a valid substring ending with char ('a' + i).
        int[] count = new int[26];
        
        int maxLength = 0;
        for (int i = 0; i < s.length(); i++) {
            // Check if the current character is consecutive to the previous one.
            // Handles both normal sequence ('b' after 'a') and wrap-around ('a' after 'z').
            if (i > 0 && (s.charAt(i) - s.charAt(i - 1) == 1 || s.charAt(i - 1) - s.charAt(i) == 25)) {
                maxLength++;
            } else {
                // If not consecutive, start a new sequence of length 1.
                maxLength = 1;
            }
            
            // Update the max length for the substring ending with s.charAt(i).
            // A longer valid substring ending with a character 'x' (e.g., "vwx")
            // naturally contains all shorter valid ones ending with 'x' (e.g., "wx", "x").
            // By storing the max length, we count all these implicitly.
            int index = s.charAt(i) - 'a';
            count[index] = Math.max(count[index], maxLength);
        }
        
        // The total number of unique substrings is the sum of these maximum lengths.
        int total = 0;
        for (int c : count) {
            total += c;
        }
        return total;
    }
}

Unique Substrings in Wraparound String in C++

class Solution {
public:
    int findSubstringInWraproundString(string s) {
        if (s.empty()) {
            return 0;
        }
        // count[i] stores the max length of a valid substring ending with char ('a' + i).
        vector<int> count(26, 0);
        
        int maxLength = 0;
        for (int i = 0; i < s.length(); ++i) {
            // Check if the current character is consecutive to the previous one.
            // Handles both normal sequence ('b' after 'a') and wrap-around ('a' after 'z').
            if (i > 0 && (s[i] - s[i-1] == 1 || s[i-1] - s[i] == 25)) {
                maxLength++;
            } else {
                // If not consecutive, start a new sequence of length 1.
                maxLength = 1;
            }
            
            // Update the max length for the substring ending with s[i].
            // We are interested in the longest one because a longer substring
            // (e.g., "abc") includes all shorter ones ending with the same character
            // (e.g., "bc", "c").
            int index = s[i] - 'a';
            count[index] = max(count[index], maxLength);
        }
        
        // The total number of unique substrings is the sum of the max lengths
        // for each ending character.
        int total = 0;
        for (int c : count) {
            total += c;
        }
        return total;
    }
};

Unique Substrings in Wraparound String in TypeScript

function findSubstringInWraproundString(s: string): number {
    if (s.length === 0) {
        return 0;
    }

    // count[i] stores the max length of a valid substring ending with char ('a' + i).
    const count = new Array(26).fill(0);
    
    let maxLength = 0;
    for (let i = 0; i < s.length; i++) {
        // Check if the current character is consecutive to the previous one.
        if (i > 0) {
            const diff = s.charCodeAt(i) - s.charCodeAt(i - 1);
            // Handles both normal sequence ('b' after 'a', diff=1) 
            // and wrap-around ('a' after 'z', diff=-25).
            if (diff === 1 || diff === -25) {
                maxLength++;
            } else {
                // If not consecutive, start a new sequence of length 1.
                maxLength = 1;
            }
        } else {
            // For the first character, the length is always 1.
            maxLength = 1;
        }

        // Update the max length for the substring ending with s[i].
        // A longer valid substring ending with a character 'x' (e.g., "vwx")
        // naturally contains all shorter valid ones ending with 'x' (e.g., "wx", "x").
        // By storing the max length, we count all these implicitly.
        const index = s.charCodeAt(i) - 'a'.charCodeAt(0);
        count[index] = Math.max(count[index], maxLength);
    }
    
    // The total number of unique substrings is the sum of these maximum lengths.
    let total = 0;
    for (const c of count) {
        total += c;
    }
    return total;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.