The string can be split into consecutive groups of identical characters. For each group of length L, the number of substrings containing only that character follows the arithmetic sequence formula: 1 + 2 + 3 + ... + L = L*(L+1)/2. We scan through the string, identify each group, and sum up the contributions.
left and right, both starting at 0.right through the string until a different character is found or the end is reached.(right - left).(length * (length + 1)) / 2 to the total.left to right to start the next group.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 totalTime complexity:
Space complexity: constant space
Where is the length of the input string
s.
For each position i, we can compute how many valid substrings end at that position. If the character at position i matches the previous character, the count equals the previous count plus 1 (we extend all previous substrings and add one new single-character substring). Otherwise, only the single character itself forms a valid substring. The total is the sum across all positions.
substrings where substrings[i] represents valid substrings ending at index i.substrings[0] = 1 and total = 1.i from 1 to n-1:s[i] equals s[i-1], set substrings[i] = substrings[i-1] + 1.substrings[i] = 1.substrings[i] to total.Time complexity:
Space complexity:
Where is the length of the input string
s.
Since we only need the previous value to compute the current one, we can optimize space by using a single variable instead of an array. This variable (count) tracks the count of valid substrings ending at the current position.
total = 1 and count = 1 (for the first character).i from 1 to n-1:s[i] equals s[i-1], increment count by 1.count to 1.count to total.Time complexity:
Space complexity: constant space
Where is the length of the input string
s.
For a group of L identical consecutive characters, the number of valid substrings is L * (L + 1) / 2, not L or L * L. This arithmetic sum counts substrings of lengths 1, 2, 3, ..., L.
# Wrong: Only counts substrings of length 1
total += length
# Wrong: Overcounts
total += length * length
# Correct: Sum of 1 + 2 + ... + L
total += length * (length + 1) // 2When iterating through the string to find groups of identical characters, the last group may not be processed if the loop only triggers on character changes. Ensure the final group is counted either by extending the loop to len(s) + 1 or by handling it after the loop ends.