Can Convert String in K Moves - Problem
Can Convert String in K Moves

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
Alphabet Shift VisualizationAlphabet Wheelabc...zshiftMove Pattern ExampleNeed shift 1 at 3 positions:• Position 0: a → b• Position 1: b → c• Position 2: c → dAvailable moves for shift 1:• Move 1: 1 % 26 = 1 ✓• Move 27: 27 % 26 = 1 ✓• Move 53: 53 % 26 = 1 ✓
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.
Asked in
Google 15 Amazon 8 Microsoft 5 Apple 3
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen