Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Number Of Changing Keys

Count how many times the pressed key changes while typing a string.

Acceptance 0%
Problem Statement

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 s representing the typed keys.
  • s may contain lowercase or uppercase letters, digits, or other printable characters depending on the platform version.

Output Format

  • Return an integer: the number of positions i such that s[i] != s[i-1].

Constraints

  • Count only adjacent changes.
  • The answer is 0 for strings of length 0 or 1.
  • Time complexity should be linear in the length of the string.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.