1. Arithmetic Sequence

class Solution:
    def countLetters(self, S: str) -> int:
        total = left = 0

        for right in range(len(S) + 1):
            if right == len(S) or S[left] != S[right]:
                len_substring = right - left
                # more details about the sum of the arithmetic sequence:
                # https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
                total += (1 + len_substring) * len_substring // 2
                left = right

        return total

Time & Space Complexity

  • Time complexity: O(N)O(N)

  • Space complexity: O(1)O(1) constant space

Where NN is the length of the input string s.


2. Dynamic Programming

class Solution:
    def countLetters(self, S: str) -> int:
        total = 1
        substrings = [0] * len(S)
        substrings[0] = 1

        for i in range(1, len(S)):
            if S[i - 1] == S[i]:
                substrings[i] = substrings[i-1] + 1
            else:
                substrings[i] = 1

            total += substrings[i]

        return total

Time & Space Complexity

  • Time complexity: O(N)O(N)

  • Space complexity: O(N)O(N)

Where NN is the length of the input string s.


3. Dynamic Programming (Optimized)

class Solution:
    def countLetters(self, S: str) -> int:
        total = 1
        count = 1
        
        for i in range(1, len(S)):
            if S[i] == S[i-1]:
                count += 1
            else:
                count = 1

            total += count

        return total

Time & Space Complexity

  • Time complexity: O(N)O(N)

  • Space complexity: O(1)O(1) constant space

Where NN is the length of the input string s.