Skip to main content
Back to problems
#1540
Medium Algorithms

Can convert string in k moves

Hash Table String
37.0% acceptance
Feb 25, 2026
427
334
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) 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. Return true if it's possible to convert s into t in no more than k moves, otherwise return false.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn can_convert_string(s: String, t: String, k: i32) -> bool {
    if s.len() != t.len() { return false; }
    let k = k as usize;
    let mut cnt = [0usize; 26]; // how many times shift d has been used
    for (sc, tc) in s.bytes().zip(t.bytes()) {
      let d = ((tc as i32 - sc as i32 + 26) % 26) as usize;
      if d == 0 { continue; }
      // i-th use of shift d requires move d + 26*(i-1)
      let m = d + 26 * cnt[d];
      if m > k { return false; }
      cnt[d] += 1;
    }
    true
  }
}