We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Changing Keys

Number: 3312

Difficulty: Easy

Paid? No

Companies: Apple, Autodesk


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.


Code Solutions

# Define a function to count the number of times the user changes keys
def count_changing_keys(s: str) -> int:
    # Initialize the key change counter to 0
    key_changes = 0
    # Iterate from the second character to the end of the string
    for i in range(1, len(s)):
        # Compare the lowercased current character with the lowercased previous character
        if s[i].lower() != s[i - 1].lower():
            # Increase the key change counter if they differ
            key_changes += 1
    # Return the count of key changes
    return key_changes

# Example usage:
s = "aAbBcC"
print(count_changing_keys(s))  # Output: 2
← Back to All Questions