Number of Changing Keys - Problem

You are given a 0-indexed string s typed by a user. Changing a key is defined as using a key different from the last used key.

For example, s = "ab" has a change of a key while s = "bBBb" does not have any.

Return the number of times the user had to change the key.

Note: Modifiers like shift or caps lock won't be counted in changing the key. That is, if a user typed the letter 'a' and then the letter 'A' then it will not be considered as a changing of key.

Input & Output

Example 1 — Basic Case with Changes
$ Input: s = "aAbBcC"
Output: 2
💡 Note: Changes occur at positions 2 (A→b) and 4 (B→c). Characters 'a'/'A', 'b'/'B', and 'c'/'C' are the same keys respectively.
Example 2 — No Changes
$ Input: s = "AaAaAaaA"
Output: 0
💡 Note: All characters represent the same key 'a', so no key changes are needed regardless of case.
Example 3 — All Different Keys
$ Input: s = "abcd"
Output: 3
💡 Note: Every adjacent pair represents different keys: a→b, b→c, c→d, resulting in 3 changes.

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of only English letters

Visualization

Tap to expand
Number of Changing Keys INPUT String s = "aAbBcC" a idx 0 A idx 1 b idx 2 B idx 3 c idx 4 C idx 5 Convert to lowercase: a a b b c c Case-insensitive comparison 'a'=='A', 'b'=='B', etc. ALGORITHM STEPS 1 Initialize count = 0, start from i=1 2 Compare Adjacent toLower(s[i]) vs toLower(s[i-1]) 3 Count Changes If different, count++ 4 Return count After full traversal Trace: i=1: a vs a (same) cnt=0 i=2: b vs a (diff) cnt=1 i=3: b vs b (same) cnt=1 i=4: c vs b (diff) cnt=2 i=5: c vs c (same) cnt=2 FINAL RESULT Key Changes Found: 2 Changes detected at: Change 1: 'a' --> 'b' Position 1 to 2 Change 2: 'b' --> 'c' Position 3 to 4 Output: 2 [OK] Key Insight: Case-insensitive comparison is crucial! Convert both characters to lowercase before comparing. 'A' and 'a' are the SAME key. Only count when the base letter changes (a-->b, b-->c, etc.) Time Complexity: O(n) | Space Complexity: O(1) - Single pass, constant space TutorialsPoint - Number of Changing Keys | Optimized Single Pass
Asked in
Microsoft 15 Apple 12 Google 8
12.5K Views
Medium Frequency
~10 min Avg. Time
245 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