Taro Logo

Unique Substrings in Wraparound String

#1 Most AskedMedium
Topics:
StringsDynamic Programming

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 are present in base.

Example 1:

Input: s = "a"
Output: 1
Explanation: Only the substring "a" of s is in base.

Example 2:

Input: s = "cac"
Output: 2
Explanation: There are two substrings ("a", "c") of s in base.

Example 3:

Input: s = "zab"
Output: 6
Explanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible length of the input string `p`, and are we guaranteed it only contains lowercase English letters?
  2. Should the count of unique substrings consider overlapping occurrences as the same, meaning we only count each distinct substring value once regardless of how many times it appears in `p`?
  3. What should be returned if the input string `p` is empty?
  4. Are there any specific time or space complexity constraints we need to target, such as $O(N)$ time?
  5. How should we handle a single-character string like 'a'—does it count as 1 unique valid substring?

Brute Force Solution

Approach

The brute force approach to finding unique substrings in a repeating alphabetical sequence involves generating every single possible piece of the sequence. Then, we check each piece to see if it follows the continuous alphabetical order and keep track of the unique ones we have seen.

Here's how the algorithm would work step-by-step:

  1. Start by looking at every possible starting point within the given text.
  2. From each starting point, carve out pieces of various lengths, going from very short pieces to pieces that span the entire remaining text.
  3. For every single piece you carve out, examine its letters to make sure they follow the strict alphabetical order where the letter after Z loops back to A.
  4. If a carved piece does not follow this alphabetical rule, throw it away and ignore it.
  5. If the piece follows the rule, check if you have already recorded this exact same piece earlier.
  6. If it is a completely new piece that you have never seen before, add it to your collection of valid finds.
  7. Continue this process until you have formed and checked every conceivable piece you can make from the text.
  8. Finally, count up all the items in your collection of unique, valid pieces to get your final answer.

Code Implementation

def findSubstringInWraproundString(input_string):
    unique_valid_pieces = set()

    for start_index in range(len(input_string)):
        for end_index in range(start_index + 1, len(input_string) + 1):
            current_piece = input_string[start_index:end_index]

            # We assume the piece is valid until proven otherwise by a broken alphabetical sequence
            is_alphabetical_order = True
            for character_index in range(len(current_piece) - 1):
                current_char_code = ord(current_piece[character_index])
                next_char_code = ord(current_piece[character_index + 1])

                if next_char_code == current_char_code + 1 or (current_char_code == 122 and next_char_code == 97):
                    continue
                else:
                    is_alphabetical_order = False
                    break

            # Only consider pieces that follow the continuous wrapround alphabetical order rule
            if is_alphabetical_order:
                unique_valid_pieces.add(current_piece)
            else:
                continue

    # Counting all accumulated unique pieces gives the final required answer
    return len(unique_valid_pieces)

Big(O) Analysis

Time Complexity
O(n³) – The time complexity is driven by three main factors: generating every possible starting point, carving out pieces of varying lengths up to the full text size, and validating whether each piece follows the alphabetical wrap-around order. With the input size n representing the length of the string, there are n choices for the starting point and n choices for the length, resulting in about n squared possible substrings. Checking each of these carved pieces requires examining its individual characters, which adds another factor proportional to n in the worst case. Combining these steps yields approximately n cubed over 2 operations, which simplifies to the final Big O time complexity of O(n³).
Space Complexity
O(N) – The brute force approach requires a collection to record every unique, valid piece found during the search. As the algorithm carves out and checks various substrings, new items are continuously added to this collection. In the worst-case scenario where all generated substrings are unique, the number of stored pieces scales with the input size N. Therefore, the auxiliary data structure driving the memory usage is this tracking collection, leading to a linear space complexity relative to N.

Optimal Solution

Approach

The problem asks for the number of unique non-empty substrings of a given string that also appear in an infinite wraparound alphabet string. Any valid substring in the wraparound string that ends at a specific character is uniquely determined by its length and its ending character. Therefore, by tracking the maximum length of contiguous wraparound sequences ending at each of the 26 lowercase English letters, we can avoid double counting and simply sum these maximum lengths.

Here's how the algorithm would work step-by-step:

  1. Initialize a dictionary to record the maximum valid substring length ending with each character, along with a counter for the current contiguous sequence length.
  2. Traverse through the input string character by character while checking if the current character follows the previous one in the wraparound alphabet.
  3. Increment the current sequence length if the contiguous wraparound condition holds; otherwise, reset the length to one.
  4. Update the stored maximum length for the current ending character whenever the current sequence length exceeds the recorded value.
  5. Sum the maximum lengths stored for all observed ending characters to get the total count of unique valid substrings.

Code Implementation

def find_substring_in_wrapround_string(text_string):
    # Track the maximum length of contiguous valid substrings ending at each character
    max_length_ending_at = {}
    current_valid_length = 0
    
    # Iterate through the characters to find lengths of contiguous sequences
    for index, current_char in enumerate(text_string):
        if index > 0 and (ord(current_char) - ord(text_string[index - 1])) % 26 == 1:
            current_valid_length += 1
        else:
            current_valid_length = 1
        
        # Update the maximum valid length ending with current_char
        previous_max = max_length_ending_at.get(current_char, 0)
        if current_valid_length > previous_max:
            max_length_ending_at[current_char] = current_valid_length
            
    # The total number of unique substrings is the sum of maximum lengths for each ending character
    return sum(max_length_ending_at.values())

Big(O) Analysis

Time Complexity
O(n) – We iterate through the input string of length n once, performing constant-time arithmetic and dictionary operations at each step.
Space Complexity
O(1) – The dictionary stores at most 26 entries corresponding to the lowercase English alphabet, which uses a constant amount of extra memory.

Edge Cases

Empty string input
How to Handle:
Return zero immediately as there are no non-empty substrings to evaluate.
Single character string
How to Handle:
Return one since any single character is inherently part of the alphabet wraparound string.
String with no consecutive alphabetical wraparounds
How to Handle:
Calculate the sum of individual unique characters by tracking a streak length of one for each.
String with repeating identical characters
How to Handle:
Keep only the maximum consecutive length ending at each character to avoid counting duplicate substrings.
Boundary wraparound from z to a
How to Handle:
Check adjacency by ensuring the current character ASCII code is exactly one greater than the previous or wraps from z to a.
Long overlapping sequences of the same substring
How to Handle:
Store the maximum streak length seen so far for each ending character in an array or hash map.
Maximum-sized input string up to constraints
How to Handle:
Iterate through the string in linear time using a fixed-size frequency array for characters to scale efficiently.
0/4 completed