Number of Changing Keys — Easy Problem & Solution

s records the keys a user typed. Changing a key means using a key different from the last one used — shift and caps lock do not count, so typing 'a' then…

  • Difficulty: Easy
  • Topics: Strings
  • Asked at: Amazon, Google, Infosys
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

s records the keys a user typed. Changing a key means using a key different from the last one used — shift and caps lock do not count, so typing 'a' then 'A' is the same key.

Return the number of times the user changed keys.

Example 1

Input: s = "CodeKairo"
Output: 8
Explanation: Every adjacent pair is a different letter.

Example 2

Input: s = "aAbBcC"
Output: 2
Explanation: `a`→`A` and `b`→`B` and `c`→`C` are all the same key; only `A`→`b` and `B`→`c` count.

Example 3

Input: s = "AaAaAaaA"
Output: 0
Explanation: One key throughout.

Constraints

  • 1 <= s.length <= 100
  • s consists only of upper and lower case English letters.

How to solve Number of Changing Keys

Walk the string comparing each character with the previous one, after folding both to lower case; count the pairs that differ.

Approach

  1. For i from 1 to n - 1, lower-case s[i] and s[i-1].
  2. Count the positions where the two differ.

Why it works

Case folding is the whole problem — the modifier keys are pressed with the letter key, so they never register as a change. Comparing raw characters would report a→A as a change and inflate the answer.

Complexity

  • Time — O(n)
  • Space — O(1)

Pitfalls

  • Comparing characters without folding case counts a→A wrongly.
  • The answer counts transitions, so it is at most n - 1.
  • A single character yields 0, not 1.

Reference solution

Python

def countKeyChanges(s: str) -> int:
    low = s.lower()
    return sum(1 for i in range(1, len(low)) if low[i] != low[i - 1])

JavaScript

var countKeyChanges = function(s) {
    var low = s.toLowerCase(), count = 0;
    for (var i = 1; i < low.length; i++) {
        if (low.charAt(i) !== low.charAt(i - 1)) count++;
    }
    return count;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 282 strings problems · the whole catalogue