#1540
Can Convert String in K Moves
MediumHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that shifting a character by x times is equivalent to shifting it by x % 26 times. We can group characters by their required shifts and ensure that we can perform the shifts within the allowed moves.
⚙️
Algorithm
3 steps- 1Step 1: Create an array to count the number of shifts needed for each character (0-25).
- 2Step 2: For each character in 's', calculate the required shift to match 't' and update the count array.
- 3Step 3: For each unique shift value, calculate how many moves are needed and check if they fit within k.
solution.py11 lines
1def canConvertString(s, t, k):
2 count = [0] * 26
3 for i in range(len(s)):
4 shift = (ord(t[i]) - ord(s[i]) + 26) % 26
5 if shift > 0:
6 count[shift] += 1
7 for i in range(1, 26):
8 if count[i] > 0:
9 if i * (count[i]) + (count[i] - 1) * 26 > k:
10 return False
11 return Trueℹ
Complexity note: The time complexity is O(n) because we only iterate through the strings a couple of times. The space complexity is O(1) since we are using a fixed-size array to count shifts.
- 1Shifting characters wraps around after 26 shifts, so we can use modulo 26 to simplify calculations.
- 2The number of moves required for each unique shift can be calculated and compared against k.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.