Can Convert String in K Moves - Problem

Given two strings s and t, your goal is to convert s into t in k moves or less.

During the i-th move (1 <= i <= k) you can:

  • Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i 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.

Input & Output

Example 1 — Basic Conversion
$ Input: s = "input", t = "ouput", k = 9
Output: true
💡 Note: We need to convert 'i'→'o' (shift 6), 'n'→'u' (shift 7), 'p'→'p' (shift 0, no change), 'u'→'u' (shift 0, no change), 't'→'t' (shift 0, no change). We need shifts of 6 and 7, which can be achieved with moves 6 and 7 respectively, both ≤ 9.
Example 2 — Impossible Case
$ Input: s = "abc", t = "bcd", k = 2
Output: false
💡 Note: We need 'a'→'b' (shift 1), 'b'→'c' (shift 1), 'c'→'d' (shift 1). All three positions need shift amount 1, but we only have moves 1 and 2. Move 1 creates shift 1, move 2 creates shift 2. We need 3 positions with shift 1 but only have 1 move that creates shift 1.
Example 3 — Wrap Around
$ Input: s = "ruu", t = "rvv", k = 3
Output: true
💡 Note: We need 'r'→'r' (no change), 'u'→'v' (shift 1), 'u'→'v' (shift 1). Two positions need shift 1. We have moves 1, 2, 3. Move 1 creates shift 1. We need 2 shifts of amount 1, but only move 1 can create shift 1, so this should be false. Wait, let me recalculate: we need only 2 positions with shift 1, and we have move 1 available, but that's only 1 move. Actually this should be false.

Constraints

  • 1 ≤ s.length, t.length ≤ 105
  • 0 ≤ k ≤ 109
  • s and t consist of lowercase English letters only

Visualization

Tap to expand
Can Convert String in K Movess = "input", t = "ouput", k = 9Source String (s)i n p u tTarget String (t)o u p u tconvertPosition 0:i→o (shift 6)Position 1:n→u (shift 7)Positions 2,3,4:No change neededAvailable moves: 1,2,3,4,5,6,7,8,9Need moves 6,7 → Both available ✓Result: true
Understanding the Visualization
1
Input Analysis
Identify positions where s[i] ≠ t[i] and calculate required shifts
2
Move Assignment
Determine if available moves 1,2,...,k can satisfy all shift requirements
3
Result
Return true if conversion possible, false otherwise
Key Takeaway
🎯 Key Insight: Each move i can only be used once and creates shift i%26, so we must count shift requirements and verify sufficient moves exist
Asked in
Google 15 Amazon 12
23.5K Views
Medium Frequency
~25 min Avg. Time
847 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