Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check one string can be converted to other by shifting characters clockwise in Python
When working with strings, we sometimes need to check if one string can be transformed into another by shifting characters clockwise in the alphabet. For example, "c" can be converted to "e" using 2 clockwise shifts (c ? d ? e).
In this problem, we have two strings p and q, and a number r representing the maximum allowed shifts. We need to determine if p can be converted to q by shifting characters clockwise at most r times in total.
Example
If p = "abc", q = "ccc", and r = 3, the answer is True because ?
- "a" can be shifted to "c" using 2 clockwise shifts (a ? b ? c)
- "b" can be shifted to "c" using 1 clockwise shift (b ? c)
- Total shifts needed: 2 + 1 = 3, which equals our limit
Algorithm
To solve this problem, we follow these steps ?
- Check if both strings have the same length
- Handle the special case where no shifts are allowed
- Calculate the total shifts needed for each character position
- For each character, find the clockwise distance in the alphabet
- Keep a running total and ensure it doesn't exceed the limit
Implementation
class Solution:
def solve(self, a, b, k):
# Check if strings have same length
if len(a) != len(b):
return False
# If no shifts allowed, strings must be identical
if k == 0 and a != b:
return False
total_shifts = 0
for i in range(len(a)):
# Calculate clockwise distance between characters
shift_needed = ord(b[i]) - ord(a[i])
# Handle wrap-around (e.g., 'z' to 'a')
if shift_needed >= 0:
total_shifts += shift_needed
else:
total_shifts += shift_needed + 26
# Check if we exceed the limit
if total_shifts > k:
return False
return True
# Test the solution
solution = Solution()
print(solution.solve("abc", "ccc", 3))
print(solution.solve("xyz", "abc", 5))
print(solution.solve("hello", "world", 10))
True False False
How It Works
The algorithm calculates the minimum clockwise shifts needed for each character position ?
- For characters where
b[i] >= a[i]: direct difference gives clockwise shifts - For characters where
b[i] < a[i]: we add 26 to handle alphabet wrap-around - We maintain a running total and return
Falseimmediately if it exceeds the limit
Key Points
- The alphabet wraps around (z ? a requires 1 shift)
- We use ASCII values with
ord()to calculate distances - Early termination optimizes performance when the limit is exceeded
- Both strings must have the same length for conversion to be possible
Conclusion
This solution efficiently checks string conversion by calculating clockwise character shifts. The algorithm runs in O(n) time complexity and handles alphabet wrap-around correctly using modular arithmetic.
