Can Convert String in K Moves — LeetCode 1540 Python Solution

MediumHash TableString
Problem
#1540
Pattern
Hash Map
Reading time
2 min

The 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) 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.

Example

Input
s = "input", t = "ouput", k = 9
Output
true
Explanation
In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.

Python solution

Python
class Solution:
    def canConvertString(self, s: str, t: str, k: int) -> bool:
        if len(s) != len(t):
            return False
        cnt = [0] * 26
        for a, b in zip(s, t):
            x = (ord(b) - ord(a) + 26) % 26
            cnt[x] += 1
        for i in range(1, 26):
            if i + 26 * (cnt[i] - 1) > k:
                return False
        return True

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1540. Can Convert String in K Moves is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1540. Can Convert String in K Moves?
LeetCode 1540. Can Convert String in K Moves is rated Medium on LeetCode.
What is the time complexity of LeetCode 1540. Can Convert String in K Moves?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1540. Can Convert String in K Moves?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1540. Can Convert String in K Moves cover?
LeetCode 1540. Can Convert String in K Moves is tagged Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview