Can Convert String in K Moves Problem
Description
LeetCode Problem 1540.
Given two strings s and t, your goal is to convert s into t in k moves or less.
During the i^th (1 <= i <= k) move you can:
- Choose any index
j(1-indexed) froms, such that1 <= j <= s.lengthandjhas not been chosen in any previous move, and shift the character at that indexitimes. - Do nothing.
Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.
Remember that any index j can be picked at most once.
Return true if it's possible to convert s into t in no more than k moves, otherwise return false.
Example 1:
Input: s = "input", t = "ouput", k = 9
Output: true
Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.
Example 2:
Input: s = "abc", t = "bcd", k = 10
Output: false
Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.
Example 3:
Input: s = "aab", t = "bbb", k = 27
Output: true
Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.
Constraints:
1 <= s.length, t.length <= 10^50 <= k <= 10^9s,tcontain only lowercase English letters.
Solution
Approach: Count the Needed Shifts
First, a move never changes the length, so if s and t have different lengths the answer is false.
For each position, the shift we need is x = (t[i] - s[i]) mod 26, a value from 0 to 25. A position with x = 0 needs nothing. A position with shift x can use move x, or x + 26, or x + 52, ..., since shifting by 26 more letters lands on the same letter. Each move number can be used only once.
So count need[x], the number of positions that need shift x. Those positions must take the move numbers x, x + 26, ..., x + 26 * (need[x] - 1), one each. The largest of them must not exceed k:
x + 26 * (need[x] - 1) <= kfor everyxfrom1to25withneed[x] > 0.
Different shifts never compete for the same move number, because x and x + 26 * c stay in their own class mod 26. That is why checking each x on its own is enough.
Complexity: O(n) time and O(1) extra space (26 counters).
class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t):
return False
# need[x] = how many positions must be shifted forward by x (mod 26)
need = [0] * 26
for a, b in zip(s, t):
need[(ord(b) - ord(a)) % 26] += 1
for x in range(1, 26):
# The positions needing shift x use moves x, x + 26, x + 52, ...
if need[x] > 0 and x + 26 * (need[x] - 1) > k:
return False
return True