#3019

Number of Changing Keys

Easy
StringString ManipulationTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution simplifies the problem by converting all characters to lowercase and then counting changes. This reduces the complexity by eliminating the need for case comparisons.

⚙️

Algorithm

4 steps
  1. 1Step 1: Convert the entire string to lowercase.
  2. 2Step 2: Initialize a counter to zero for key changes.
  3. 3Step 3: Loop through the string from the second character to the end.
  4. 4Step 4: Compare each character with the previous one. If they are different, increment the counter.
solution.py12 lines
1# Full working Python code
2
3def count_key_changes(s):
4    s = s.lower()
5    changes = 0
6    for i in range(1, len(s)):
7        if s[i] != s[i - 1]:
8            changes += 1
9    return changes
10
11# Example usage
12print(count_key_changes('aAbBcC'))  # Output: 2

Complexity note: The time complexity is O(n) because we traverse the string once. The space complexity is O(n) due to the creation of a new string when converting to lowercase.

  • 1Changing keys is only counted when the letter changes, not the case.
  • 2Converting to lowercase simplifies the comparison process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.