Count how many times the pressed key changes while typing a string.
Problem
You are given a string representing the keys typed in order. Count how many times the key changes from one character to the next while scanning the string from left to right.
A change is counted whenever two adjacent characters are different. The first character does not count as a change.
Return the total number of changing keys.
Notes
- The string is treated as a sequence of individual characters.
- Only transitions between neighboring characters matter.
- If the string is empty or has one character, the answer is
0.
Input Format
- A string
srepresenting the typed keys. smay contain lowercase or uppercase letters, digits, or other printable characters depending on the platform version.
Output Format
- Return an integer: the number of positions
isuch thats[i] != s[i-1].
Constraints
- Count only adjacent changes.
- The answer is
0for strings of length0or1. - Time complexity should be linear in the length of the string.
Example 1
Input
s = "aabbcc"
Output
2
Explanation
The transitions are a->a (no), a->b (yes), b->b (no), b->c (yes), c->c (no). Total changes = 2.
Example 2
Input
s = "aaaa"
Output
0
Explanation
No adjacent characters are different.
Show 1 more example
Example 3
Input
s = "abca"
Output
3
Explanation
a->b, b->c, and c->a are all changes.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.