#3019
Easy Algorithms Number of changing keys
String
80.5% acceptance
Feb 25, 2026
163
18
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn count_key_changes(s: String) -> i32 {
let s: Vec<u8> = s.bytes().map(|b| b.to_ascii_lowercase()).collect();
s.windows(2).filter(|w| w[0] != w[1]).count() as i32
}
}