Taro Logo

Count Complete Substrings

Hard
Asked by:
Profile picture
3 views
Topics:
StringsTwo PointersSliding Windows

You are given a string word and an integer k.

A substring s of word is complete if:

  • Each character in s occurs exactly k times.
  • The difference between two adjacent characters is at most 2. That is, for any two adjacent characters c1 and c2 in s, the absolute difference in their positions in the alphabet is at most 2.

Return the number of complete substrings of word.

A substring is a non-empty contiguous sequence of characters in a string.

Example 1:

Input: word = "igigee", k = 2
Output: 3
Explanation: The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: igigee, igigee, igigee.

Example 2:

Input: word = "aaabbbccc", k = 3
Output: 6
Explanation: The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc.

Constraints:

  • 1 <= word.length <= 105
  • word consists only of lowercase English letters.
  • 1 <= k <= word.length

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 length of the string `word` and the possible range of values for `k`?
  2. How should we handle cases where the string `word` is empty or shorter than $k$ characters?
  3. When checking the alphabetical difference between adjacent characters, is the comparison case-sensitive, or should we assume the string contains only lowercase English letters?
  4. Does the condition "difference in alphabetical order between any two adjacent characters is at most two" mean absolute difference (e.g., $|code(a) - code(b)| e 2$), and does it apply circularly (like 'z' and 'a') or strictly along the standard alphabet?
  5. If multiple distinct complete substrings overlap within `word`, should they be counted individually based on their start and end indices?

Brute Force Solution

Approach

The brute force approach is the most straightforward way to solve the problem by exhaustively checking every single possible smaller piece of the given text. We will examine every possible starting and ending point within the text to test all potential substrings.

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

  1. Begin by looking at every possible starting position within the text.
  2. From each starting position, consider every possible ending position that forms a contiguous chunk of letters.
  3. For every single chunk you look at, check two special rules.
  4. First, check if all the letters inside your current chunk appear the exact same number of times.
  5. Second, check if any two neighboring letters in your chunk are close to each other in the alphabet, meaning they are not too far apart.
  6. If your chunk passes both of these tests, count it as a successful find.
  7. Repeat this process for every possible chunk in the entire text, and add up all the successes to get your final answer.

Code Implementation

class Solution:
    def countCompleteSubstrings(self, text: str, target_frequency: int) -> int:
        total_successful_count = 0
        string_length = len(text)
        
        # We iterate over every possible starting position to exhaustively check all substrings
        for start_position in range(string_length):
            
            for end_position in range(start_position, string_length):
                current_substring = text[start_position:end_position + 1]
                is_alphabetically_close = True
                
                # We verify the adjacency rule because adjacent characters cannot exceed distance two
                for character_index in range(len(current_substring) - 1):
                    if abs(ord(current_substring[character_index]) - ord(current_substring[character_index + 1])) > 2:
                        is_alphabetically_close = False
                        break
                
                if not is_alphabetically_close:
                    continue
                
                character_frequencies = {}
                for letter in current_substring:
                    character_frequencies[letter] = character_frequencies.get(letter, 0) + 1
                
                # We ensure all distinct characters in the substring match the required frequency
                all_frequencies_match = True
                for frequency_value in character_frequencies.values():
                    if frequency_value != target_frequency:
                        all_frequencies_match = False
                        break
                
                if all_frequencies_match:
                    total_successful_count += 1
                    
        return total_successful_count

Big(O) Analysis

Time Complexity
O(n³) – For a string of length n, there are approximately n * n / 2 possible starting and ending positions to form every substring chunk. For each of these generated chunks, we iterate through its characters to check the frequency and adjacency rules, which takes up to n additional operations. This leads to approximately n cubed over 2 operations when combining the chunk generation and validation steps, which simplifies to O(n³) in the worst case.
Space Complexity
O(1) – The brute force approach evaluates every possible starting and ending position without allocating auxiliary data structures whose size scales with the input string length N. Only a few primitive variables are used to track indices, counts, and validation checks as we iterate through the contiguous chunks. Consequently, the extra memory consumption remains constant regardless of how large the input string becomes.

Optimal Solution

Approach

To find all the special pieces within a text efficiently, we first break the text into smaller segments wherever the distance between neighboring letters becomes too large. Within each continuous segment, we use a sliding window technique to check every possible alphabet size constraint without starting our searches from scratch.

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

  1. Scan through the text and place boundary markers wherever two adjacent letters are too far apart in the alphabet from each other, which means no valid substring can cross that gap.
  2. Treat each separated piece of text independently, since any valid substring must lie entirely within one of these pieces.
  3. For each piece, determine how many unique letters your target substring is allowed to contain, remembering that the total length of the substring must match a specific multiple of that unique letter count.
  4. Slide a window of the exact required length across the text piece, keeping track of how many times each letter appears inside the window.
  5. Check if every letter present in the window appears the exact required number of times and no letter violates the strict alphabet neighbor distance limit.
  6. Whenever the letter counts and neighbor distances match the requirements, count that window as a valid finding.
  7. Change the target unique letter count to test other allowed sizes, repeating the sliding window check until all possibilities for the current piece are explored.

Code Implementation

class Solution:
    def countCompleteSubstrings(self, word: str, k: int) -> int:
        text_length = len(word)
        total_valid_count = 0
        
        # We segment the string where adjacent characters differ by more than 2 in the alphabet.
        segment_start_index = 0
        for current_index in range(1, text_length + 1):
            if current_index == text_length or abs(ord(word[current_index]) - ord(word[current_index - 1])) > 2:
                current_segment = word[segment_start_index:current_index]
                
                # We test each possible number of unique characters because valid lengths depend on it.
                for unique_count in range(1, 27):
                    window_size = unique_count * k
                    if window_size > len(current_segment):
                        break
                        
                    letter_counts = [0] * 26
                    valid_window_count = 0
                    
                    for window_index in range(len(current_segment)):
                        letter_index = ord(current_segment[window_index]) - ord('a')
                        letter_counts[letter_index] += 1
                        
                        if window_index >= window_size:
                            outgoing_index = ord(current_segment[window_index - window_size]) - ord('a')
                            letter_counts[outgoing_index] -= 1
                            
                        if window_index >= window_size - 1:
                            # We ensure every present letter matches the exact required frequency of k.
                            is_valid = True
                            for check_index in range(26):
                                if letter_counts[check_index] > 0 and letter_counts[check_index] != k:
                                    is_valid = False
                                    break
                            if is_valid:
                                total_valid_count += 1
                                
                segment_start_index = current_index
                
        # The total count accumulates all valid sliding windows found across all text segments.
        return total_valid_count

Big(O) Analysis

Time Complexity
O(26 * n) – The input string of length n is first scanned in linear time to split it into continuous segments based on adjacent character differences. For each segment, we iterate through 26 possible counts for the number of unique target letters. Within each unique letter count iteration, a sliding window of length equal to 26 times the unique count moves across the segment in linear time relative to the segment length. Since the number of unique letter counts is a constant capped at 26, the sliding window operations take at most 26 times the length of the string. Summing these operations across all segments results in approximately 26 * n steps, which simplifies to a linear time complexity of O(n).
Space Complexity
O(1) – The auxiliary space used is constant because the sliding window and frequency tracking require fixed-size data structures of at most 26 elements corresponding to the English alphabet. The boundary markers and loop variables consume a negligible amount of memory that does not scale with the input string length N. Therefore, the extra memory remains bounded regardless of how large the input text grows.

Edge Cases

String length is less than k
How to Handle:
The algorithm should immediately return zero since no substring can satisfy the frequency requirement.
String contains all identical characters like aaaaa
How to Handle:
The sliding window correctly identifies valid blocks where frequency equals k and adjacent character differences are zero.
Adjacent characters exceed the alphabetical difference limit of two
How to Handle:
The condition breaks the current window segment and restarts the tracking from the new character.
Alphabet size varies from 1 up to 26 distinct characters
How to Handle:
Since there are at most 26 possible unique characters, checking all possible distinct character counts from 1 to 26 runs in optimal linear time.
Maximum length constraints up to 105 characters
How to Handle:
Using an O(n) sliding window approach per unique character count ensures the solution scales efficiently without TLE.
No complete substrings exist in the input
How to Handle:
The counter remains at zero and the function correctly returns 0.
Substrings with overlapping valid regions
How to Handle:
The sliding window accurately evaluates every valid window size independently without missing nested or overlapping matches.
Input string with alternating characters separated by gaps exceeding the difference limit
How to Handle:
The split logic based on adjacent differences correctly segments the string into continuous valid blocks before running the frequency checks.