You are given a string word and an integer k.
A substring s of word is complete if:
s occurs exactly k times.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 <= 105word consists only of lowercase English letters.1 <= k <= word.lengthWhen 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:
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:
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_countTo 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:
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| Case | How to Handle |
|---|---|
| String length is less than k | The algorithm should immediately return zero since no substring can satisfy the frequency requirement. |
| String contains all identical characters like aaaaa | 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 | 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 | 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 | 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 | The counter remains at zero and the function correctly returns 0. |
| Substrings with overlapping valid regions | 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 | The split logic based on adjacent differences correctly segments the string into continuous valid blocks before running the frequency checks. |