Number of Changing Keys — Solution in Python, Java & C++
Number of Changing Keys solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.
Number of Changing Keys is an easy coding problem on strings, asked in Amazon, Google and Infosys interviews.
- 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 <= 100s consists only of upper and lower case English letters.
Hints for Number of Changing Keys
Hint 1
Fold both characters to the same case before comparing them.
Hint 2
Only adjacent pairs matter — this is one pass.
Hint 3
A string of length 1 has no pairs, so the answer is 0.
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
- For
ifrom 1 ton - 1, lower-cases[i]ands[i-1]. - 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→Awrongly. - 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])Java
public static int countKeyChanges(String s) {
String low = s.toLowerCase();
int count = 0;
for (int i = 1; i < low.length(); i++) {
if (low.charAt(i) != low.charAt(i - 1)) count++;
}
return count;
}C++
int countKeyChanges(string s) {
int count = 0;
for (size_t i = 1; i < s.size(); i++) {
char a = (char) tolower(s[i]);
char b = (char) tolower(s[i - 1]);
if (a != b) count++;
}
return count;
}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#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings