Count Adjacent Repeated Characters in a String

Quick Overview

Given a lowercase string of up to a million characters, count the indices where a character equals the one right after it. It tests loop bounds that avoid an off-by-one error and a pass over the string that uses constant extra space.

Count Adjacent Repeated Characters in a String

Company: Elastic

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a string `s`, count the total number of consecutive character repetitions. A repetition is a pair of adjacent characters that are the same. Formally, count the number of indices `i` (where `0 <= i < len(s) - 1`) such that `s[i] == s[i + 1]`. Return the total count of such repetitions. ### Function Signature ```python def count_repetitions(s: str) -> int: ``` ### Constraints - `1 <= len(s) <= 10^6` - `s` consists of lowercase English letters. ### Examples ```text Input: s = "aabbc" Output: 2 ``` The pairs at indices (0, 1) and (2, 3) are equal ('a' with 'a', 'b' with 'b'). No other adjacent pair matches. ```text Input: s = "aaabbbccc" Output: 6 ``` The equal pairs are (0, 1) and (1, 2) for 'a', (3, 4) and (4, 5) for 'b', and (6, 7) and (7, 8) for 'c'. The pairs that cross from one letter to the next do not match. ```text Input: s = "z" Output: 0 ``` A string of length 1 has no adjacent pair, so there are no repetitions.

Overview: Given a lowercase string of up to a million characters, count the indices where a character equals the one right after it. It tests loop bounds that avoid an off-by-one error and a pass over the string that uses constant extra space.

Elastic logo
Elastic
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a string s, count the total number of consecutive character repetitions.

A repetition is a pair of adjacent characters that are the same. Formally, count the number of indices i (where 0 <= i < len(s) - 1) such that s[i] == s[i + 1].

Return the total count of such repetitions.

Function Signature

def count_repetitions(s: str) -> int:

Constraints

  • 1 <= len(s) <= 10^6
  • s consists of lowercase English letters.

Examples

Input: s = "aabbc"
Output: 2

The pairs at indices (0, 1) and (2, 3) are equal ('a' with 'a', 'b' with 'b'). No other adjacent pair matches.

Input: s = "aaabbbccc"
Output: 6

The equal pairs are (0, 1) and (1, 2) for 'a', (3, 4) and (4, 5) for 'b', and (6, 7) and (7, 8) for 'c'. The pairs that cross from one letter to the next do not match.

Input: s = "z"
Output: 0

A string of length 1 has no adjacent pair, so there are no repetitions.