Problem
Given two strings s
and t
, your goal is to convert s
into t
in k
**** moves or less.
During the ith
(1 <= i <= k
) move you can:
- Choose any index
j
(1-indexed) froms
, such that1 <= j <= s.length
andj
has not been chosen in any previous move, and shift the character at that indexi
times. - 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
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s
,t
contain only lowercase English letters.
Solution
Method 1 – Greedy Counting of Required Shifts
Intuition
For each character, calculate how many shifts are needed to convert s[i]
to t[i]
(modulo 26). For each possible shift, count how many times it is needed. Since each shift of value x
can only be performed once every 26 moves (i.e., at moves x, x+26, x+52, …), check if the required number of shifts for each value fits within k
moves.
Approach
- If
s
andt
are not the same length, return false. - For each index, compute the shift needed:
(ord(t[i]) - ord(s[i])) % 26
. - For each shift value from 1 to 25, count how many times it is needed.
- For each shift value
x
, the last time it can be performed isx + 26 * (count[x] - 1)
. If this exceedsk
, return false. - If all shifts fit within
k
, return true.
Code
|
|
|
|
Complexity
- ⏰ Time complexity: O(n)
- 🧺 Space complexity: O(1)