Taro Logo

Count Substrings with Only One Distinct Letter

Easy
Asked by:
Virtu Financial
4 views
Topics:
StringsTwo PointersSliding Windows

Given a string s, return the number of substrings that have only one distinct letter.

Example 1:

Input: s = "aaaba"
Output: 8
Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
"aaa" occurs 1 time.
"aa" occurs 2 times.
"a" occurs 4 times.
"b" occurs 1 time.
So the answer is 1 + 2 + 4 + 1 = 8.

Example 2:

Input: s = "aaaaaaaaaa"
Output: 55

Constraints:

  • 1 <= s.length <= 1000
  • s[i] consists of only 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 character set of the input string `s`? Are we guaranteed it only contains lowercase English letters, or could it include uppercase letters, numbers, or Unicode/special characters?
  2. What is the maximum expected length of the input string `s`?
  3. How should we handle an empty string or a null input? Should it return 0?
  4. Are identical substrings that appear at different starting indices in the string considered distinct, or do we count all valid contiguous index ranges?
  5. Does the definition of a substring with 'only one distinct letter' mean that a single character by itself is considered a valid substring of length 1?

Brute Force Solution

Approach

To find all the special pieces of text where every single letter is exactly the same, the brute force approach is to check every possible piece you can possibly cut out from the main text. By systematically looking at every single starting point and trying out every possible ending point, we can examine all potential pieces one by one.

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

  1. Begin at the very first letter of the text.
  2. Consider every possible way to cut a piece of text starting from this position, making the piece longer one letter at a time.
  3. For each piece you look at, check every single letter inside it to see if they are all identical.
  4. If every letter in that piece is the same, count it as a successful finding.
  5. Once you have checked all possible lengths starting from the current position, move your starting point to the next letter in the text.
  6. Repeat the process of checking every possible length from this new starting point.
  7. Continue this exhaustive search until every single possible piece of text has been examined and your collection of successful findings is complete.

Code Implementation

def count_letters(text):    total_count = 0        # We examine every possible starting point to ensure no substring is missed during the search    for start_index in range(len(text)):        for end_index in range(start_index, len(text)):            substring = text[start_index:end_index + 1]                        # A set allows us to efficiently determine if all characters in the substring are identical            if len(set(substring)) == 1:                total_count += 1    # Returning the accumulated sum provides the total count of valid uniform substrings    return total_count

Big(O) Analysis

Time Complexity
O(n³) – The brute force strategy uses nested loops where the outer loop sets the starting position and the inner loop sets the ending position for every possible substring of length n. Because we also validate every single character inside each piece to ensure they are all identical, we add an extra linear scan operation for every candidate substring. This results in approximately n cubed over 6 operations as we systematically check all possible lengths and starting points, which simplifies to O(n³) in Big O notation.
Space Complexity
O(1) – The brute force approach described relies entirely on iterating through starting points and ending points using simple scalar index variables like counters and flags. No auxiliary data structures, temporary lists, or recursion stacks are created during the process. The extra memory used remains constant regardless of how long the input text is, because only a fixed number of primitive variables are maintained in memory. Therefore, the auxiliary space complexity is constant, simplifying to Big O of 1.

Optimal Solution

Approach

Instead of checking every single smaller piece of text one by one, the optimal approach looks at the big picture by identifying unbroken blocks of identical letters. By figuring out how many smaller pieces can be made from each uninterrupted block using a simple math shortcut, we can quickly count everything without wasting time.

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

  1. Scan through the text from start to finish to find uninterrupted sections where every single character is completely identical.
  2. Measure how long each of these identical sections is by counting how many characters it contains.
  3. For any given section of identical characters, realize that the number of smaller pieces you can make from it follows a very predictable counting pattern based on its length.
  4. Calculate the total number of smaller pieces for that specific section using this quick shortcut instead of manually listing them out.
  5. Repeat this counting process for every other identical section found throughout the text.
  6. Add up all the results from every section to get the final total, giving you the complete answer instantly.

Code Implementation

def count_letters(input_string):
    total_substring_count = 0
    current_block_length = 0
    string_length = len(input_string)

    # We scan through the text to find uninterrupted sections of identical letters.
    for character_index in range(string_length):
        current_block_length += 1

        if character_index == string_length - 1 or input_string[character_index] != input_string[character_index + 1]:
            # The math shortcut calculates all possible smaller pieces from this identical section length.
            total_substring_count += current_block_length * (current_block_length + 1) // 2
            current_block_length = 0

    # We sum up all contributions from every identical section to get the final total.
    return total_substring_count

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass through the input string of size n to identify and measure unbroken blocks of identical characters. As the algorithm scans the string from start to finish, it performs constant time math operations for each block length. This straightforward linear traversal requires approximately n operations in total, which simplifies to O(n).
Space Complexity
O(1) – The algorithm processes the input string in a single pass using only a few primitive variables, such as a counter for the current streak length and a total sum accumulator. No auxiliary data structures, temporary lists, or recursion stack frames are created regardless of the input size N. Therefore, the extra memory required remains constant and does not scale with the length of the string.

Edge Cases

Empty string input
How to Handle:
Return zero immediately since there are no substrings to evaluate.
String with a single character
How to Handle:
Return one because the single character itself forms a valid substring of length one.
String with all identical characters such as aaaa
How to Handle:
Compute the total count using the arithmetic progression formula n times n plus one over two.
String with all alternating distinct characters such as ababab
How to Handle:
Reset the running streak length to one every time a character changes to correctly count individual characters.
Maximum length string within constraints
How to Handle:
Use a single pass linear scan with an accumulator to ensure optimal execution time and avoid memory limits.
Integer overflow from very long strings of identical characters
How to Handle:
Accumulate the total count using a sixty four bit integer data type to prevent arithmetic overflow.