MOD = 10**9 + 7def countHomogenous(s): n = len(s) count = 0 slow, fast = 0, 0 while fast < n: if s[fast] != s[slow]: count += (fast - slow) * (fast - slow + 1) // 2 count %= MOD slow = fast fast += 1 count += (fast - slow) * (fast - slow + 1) // 2 count %= MOD return count# Test casess1 = "abbcccaa"s2 = "xy"s3 = "zzzzz"print(countHomogenous(s1)) # Output: 13print(countHomogenous(s2)) # Output: 2print(countHomogenous(s3)) # Output: 15
Attempt 1
If all characters of a string a same.
Here Fast & Slow Pointers Algorithm can be used but how to decide the number, lets say if slow and fast pointer are same then +2 store this value and do +1 in that and then add that to the main sum?