Problem Description
Given a 0-indexed string s that represents the sequence of keys pressed by a user, determine the number of times the user had to change the key. A key change is defined as pressing a key that is different from the last used key. Note that switching between uppercase and lowercase of the same letter (e.g., 'a' to 'A') is not considered a key change.
Key Insights
- Only the alphabet character (irrespective of case) matters when determining if the key has changed.
- By converting characters to a uniform case (lowercase or uppercase), adjacent comparisons become straightforward.
- A simple linear iteration through the string suffices to count key changes.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the string. Space Complexity: O(1)
Solution
The solution involves traversing the string from the second character onward and comparing it with the previous one after converting both characters to lowercase. If they differ, it indicates a change in the key, and we increment a counter. This approach uses minimal extra memory and only one pass through the string, making it efficient.