Number of Changing Keys - Problem

Imagine you're typing on a keyboard and want to track how many times you switch between different keys. You are given a 0-indexed string s that represents the sequence of characters a user typed.

A key change occurs when the user presses a different physical key than the one they just pressed. For example:

  • "ab" has 1 key change (from 'a' to 'b')
  • "bBBb" has 0 key changes (all are the same 'b' key, just with different cases)
  • "aAbBcC" has 2 key changes ('a'โ†’'b', 'b'โ†’'c')

Important: Case doesn't matter! Typing 'a' then 'A' is not considered a key change since it's the same physical key (just with Shift or Caps Lock). Return the total number of times the user had to change keys.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "aAbBcC"
โ€บ Output: 2
๐Ÿ’ก Note: The key changes are: 'a'โ†’'b' (indices 1โ†’2) and 'b'โ†’'c' (indices 3โ†’4). Note that 'a'โ†’'A' and 'b'โ†’'B' and 'c'โ†’'C' are not key changes since they're the same physical keys.
example_2.py โ€” No Changes
$ Input: s = "AaAaAa"
โ€บ Output: 0
๐Ÿ’ก Note: All characters represent the same physical key 'a', just with different cases. No key changes occur.
example_3.py โ€” All Different
$ Input: s = "abc"
โ€บ Output: 2
๐Ÿ’ก Note: Every adjacent pair represents different keys: 'a'โ†’'b' and 'b'โ†’'c', giving us 2 key changes total.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of only English letters (uppercase and lowercase)
  • Case insensitive: 'a' and 'A' represent the same key

Visualization

Tap to expand
Keyboard Key Changes: "Hello"HKey: HPosition 0eKey: EPosition 1lKey: LPosition 2lKey: LPosition 3oKey: OPosition 4CHANGECHANGESAMECHANGEKey Change Analysisโ€ข H โ†’ e: Different keys โœ— (+1 change)โ€ข e โ†’ l: Different keys โœ— (+1 change)โ€ข l โ†’ l: Same key โœ“ (no change)โ€ข l โ†’ o: Different keys โœ— (+1 change)3Total Changes
Understanding the Visualization
1
Start typing
Begin with the first character - no change yet since there's no previous key
2
Compare with previous
For each new character, compare it with the previous one (ignoring case)
3
Count the changes
If the physical keys are different, increment our counter
4
Continue until end
Repeat this process for every character in the string
Key Takeaway
๐ŸŽฏ Key Insight: We only need to compare adjacent characters in a single pass, making this an O(n) time, O(1) space solution.
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 25
23.6K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen