Program to check whether we can convert string in K moves or not using Python

In this problem, we need to determine if we can convert string s to string t using at most k moves. In the i-th move, we can select an unused index and shift the character at that position i times forward in the alphabet (with wrapping from 'z' to 'a').

Problem Understanding

The key insight is that in move i, we can shift a character by exactly i positions. Since the alphabet wraps around, we need to calculate how many times each required shift distance can be achieved within k moves.

Algorithm Steps

  • Check if both strings have the same length

  • Calculate how many times each shift distance (0-25) can be performed

  • For each character pair, check if the required shift is available

Example

Let's trace through the example where s = "poput", t = "vwput", k = 9 ?

def solve(s, t, k):
    if len(s) != len(t):
        return False
    
    # Calculate available moves for each shift distance
    count = [min(1, k - i + 1) + (k - i)//26 for i in range(26)]
    
    for c1, c2 in zip(s, t):
        if c1 != c2:
            # Calculate required shift distance
            diff = (ord(c2) - ord(c1) + 26) % 26
            if count[diff] <= 0:
                return False
            count[diff] -= 1
    
    return True

# Test the example
s = "poput"
t = "vwput"
k = 9

print(f"Can convert '{s}' to '{t}' in {k} moves: {solve(s, t, k)}")
Can convert 'poput' to 'vwput' in 9 moves: True

How It Works

The solution works by pre-calculating how many times each shift distance can be achieved ?

def explain_counting(k):
    print(f"For k = {k} moves:")
    print("Shift\tAvailable Times")
    print("-" * 25)
    
    for i in range(10):  # Show first 10 shift distances
        count = min(1, k - i + 1) + (k - i) // 26
        print(f"{i}\t{count}")

explain_counting(9)
For k = 9 moves:
Shift	Available Times
-------------------------
0	10
1	9
2	8
3	7
4	6
5	5
6	4
7	3
8	2
9	1

Step-by-Step Analysis

For the example "poput" ? "vwput" ?

def analyze_conversion(s, t, k):
    print(f"Converting '{s}' to '{t}' with k={k}")
    print("Position\tFrom\tTo\tShift\tMove Used")
    print("-" * 45)
    
    for i, (c1, c2) in enumerate(zip(s, t)):
        if c1 != c2:
            diff = (ord(c2) - ord(c1) + 26) % 26
            print(f"{i}\t\t{c1}\t{c2}\t{diff}\tMove {diff}")
        else:
            print(f"{i}\t\t{c1}\t{c2}\t0\tNo move")

analyze_conversion("poput", "vwput", 9)
Converting 'poput' to 'vwput' with k=9
Position	From	To	Shift	Move Used
---------------------------------------------
0		p	v	6	Move 6
1		o	w	8	Move 8
2		p	p	0	No move
3		u	u	0	No move
4		t	t	0	No move

Edge Cases

# Test different scenarios
test_cases = [
    ("abc", "def", 5),    # Each char needs shift 3
    ("xyz", "abc", 10),   # Wrapping around alphabet
    ("hello", "world", 3) # Not enough moves
]

for s, t, k in test_cases:
    result = solve(s, t, k)
    print(f"'{s}' ? '{t}' with k={k}: {result}")
'abc' ? 'def' with k=5: True
'xyz' ? 'abc' with k=10: True
'hello' ? 'world' with k=3: False

Conclusion

This algorithm efficiently determines if string conversion is possible by pre-calculating available moves for each shift distance. The time complexity is O(n) where n is the string length, making it optimal for this constraint-based transformation problem.

Updated on: 2026-03-25T21:01:36+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements