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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code