Can Convert String in K Moves - Problem
Can Convert String in K Moves
You're given two strings
The Rules:
• In move
• Shift the character at position
• Alphabet wraps around: 'z' + 1 = 'a'
• Each index can only be used once
• You can also choose to do nothing in a move
Goal: Return
Example: To change 'a' to 'c', you need 2 shifts. You could use this in move 2, or wait for a later move that gives exactly 2 shifts (like move 28, since (28-2) % 26 = 0).
You're given two strings
s and t of equal length, and your mission is to transform s into t using at most k moves. This is like a puzzle where you need to strategically shift characters in the alphabet!The Rules:
• In move
i (where i goes from 1 to k), you can pick any unused index j from string s• Shift the character at position
j exactly i positions forward in the alphabet• Alphabet wraps around: 'z' + 1 = 'a'
• Each index can only be used once
• You can also choose to do nothing in a move
Goal: Return
true if transformation is possible, false otherwise.Example: To change 'a' to 'c', you need 2 shifts. You could use this in move 2, or wait for a later move that gives exactly 2 shifts (like move 28, since (28-2) % 26 = 0).
Input & Output
example_1.py — Basic Case
$
Input:
s = "input", t = "ouput", k = 9
›
Output:
true
💡 Note:
We need to change 'i'→'o' (shift 6) and 'n'→'p' (shift 2). Move 6 gives shift 6, move 2 gives shift 2. Both moves ≤ 9, so it's possible.
example_2.py — Insufficient Moves
$
Input:
s = "abc", t = "bcd", k = 2
›
Output:
false
💡 Note:
All three positions need shift 1. Only move 1 provides shift 1 within k=2 moves. We need 3 such moves but only have 1.
example_3.py — Wrap Around
$
Input:
s = "aab", t = "bbc", k = 27
›
Output:
true
💡 Note:
Position 0: 'a'→'b' needs shift 1 (use move 1). Position 2: 'b'→'c' needs shift 1 (use move 27, since 27%26=1). Two positions need same shift, and we have moves 1 and 27.
Constraints
- 1 ≤ s.length, t.length ≤ 105
- 0 ≤ k ≤ 109
- s.length == t.length
- s and t consist of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Shifts
For each position, find how many steps forward we need to go from s[i] to t[i]
2
Group by Remainder
Group positions by their shift amount modulo 26 (since alphabet wraps)
3
Count Available Moves
For shift amount r, moves r, r+26, r+52, ... all work
4
Verify Sufficiency
Check if we have enough moves of each type within the k limit
Key Takeaway
🎯 Key Insight: The circular nature of alphabets means moves repeat every 26 steps. Count requirements by remainder class, then verify sufficient moves exist in each class.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code