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
Check if it is possible to transform one string to another in Python
When we need to check if one string can be transformed into another by converting lowercase letters to uppercase and removing remaining lowercase letters, we can use dynamic programming to solve this step by step.
Given two strings s and t (where t is in uppercase), we need to determine if we can transform s to t by performing these operations:
- Convert some lowercase letters to uppercase
- Remove all remaining lowercase letters
Problem Understanding
For example, if s = "fanToM" and t = "TOM", we can:
- Convert 'o' to 'O'
- Remove lowercase letters 'f', 'a', 'n' to get "TOM"
Dynamic Programming Approach
We'll use a 2D DP table where dp[i][j] represents whether we can transform the first i characters of s to match the first j characters of t.
Algorithm Steps
- Create a DP matrix of size
(n+1) × (m+1)initialized withFalse - Set
dp[0][0] = True(empty strings match) - For each character in
s, check if we can match it with a character intor skip it - Return
dp[n][m]as the final result
Example
def can_transform_string(s, t):
n = len(s)
m = len(t)
# Create DP table
dp = [[False for j in range(m + 1)] for i in range(n + 1)]
dp[0][0] = True
for i in range(len(s)):
for j in range(len(t) + 1):
if dp[i][j]:
# Try to match current character with target
if j < len(t) and s[i].upper() == t[j]:
dp[i + 1][j + 1] = True
# Skip current character if it's lowercase
if not s[i].isupper():
dp[i + 1][j] = True
return dp[n][m]
# Test the function
s = "fanToM"
t = "TOM"
result = can_transform_string(s, t)
print(f"Can transform '{s}' to '{t}': {result}")
Can transform 'fanToM' to 'TOM': True
Step-by-Step Trace
Let's trace through the example s = "fanToM" and t = "TOM":
def trace_transformation(s, t):
n, m = len(s), len(t)
dp = [[False] * (m + 1) for _ in range(n + 1)]
dp[0][0] = True
print(f"Transforming '{s}' to '{t}'")
print("DP table progress:")
for i in range(len(s)):
for j in range(len(t) + 1):
if dp[i][j]:
char = s[i]
print(f" Processing '{char}' at position {i}")
# Try to match with target
if j < len(t) and char.upper() == t[j]:
dp[i + 1][j + 1] = True
print(f" Matched '{char}' with '{t[j]}'")
# Skip if lowercase
if not char.isupper():
dp[i + 1][j] = True
print(f" Skipped lowercase '{char}'")
return dp[n][m]
# Trace the example
s = "fanToM"
t = "TOM"
result = trace_transformation(s, t)
print(f"\nFinal result: {result}")
Transforming 'fanToM' to 'TOM'
DP table progress:
Processing 'f' at position 0
Skipped lowercase 'f'
Processing 'a' at position 1
Skipped lowercase 'a'
Processing 'n' at position 2
Skipped lowercase 'n'
Processing 'T' at position 3
Matched 'T' with 'T'
Processing 'o' at position 4
Matched 'o' with 'O'
Skipped lowercase 'o'
Processing 'M' at position 5
Matched 'M' with 'M'
Final result: True
Additional Test Cases
# Test with different cases
test_cases = [
("abc", "ABC"), # All lowercase to uppercase
("AbC", "ABC"), # Mixed case
("hello", "HI"), # Impossible transformation
("Python", "PY"), # Partial match with removal
]
for s, t in test_cases:
result = can_transform_string(s, t)
print(f"'{s}' ? '{t}': {result}")
'abc' ? 'ABC': True 'AbC' ? 'ABC': True 'hello' ? 'HI': False 'Python' ? 'PY': True
How It Works
The algorithm uses dynamic programming where each state dp[i][j] indicates whether we can transform the first i characters of string s into the first j characters of string t. For each character, we have two choices: match it with the target (if possible) or skip it (if it's lowercase).
Conclusion
This dynamic programming solution efficiently determines if string transformation is possible by tracking all valid states. The time complexity is O(n×m) where n and m are the lengths of the input strings.
