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
Selected Reading
Check whether given string can be generated after concatenating given strings in Python
In Python, we often need to check whether a given string can be formed by concatenating two other strings in either order. This problem involves verifying if string r equals s + t or t + s.
For example, if we have strings s = "world", t = "hello", and r = "helloworld", we need to check if r can be formed by concatenating s and t in either order.
Algorithm
To solve this problem, we follow these steps ?
- First, check if the length of
requals the sum of lengths ofsandt - If
rstarts withs, check if it ends witht - If
rstarts witht, check if it ends withs - Return
Trueif either condition is satisfied, otherwise returnFalse
Implementation
def solve(s, t, r):
# Check if lengths match
if len(r) != len(s) + len(t):
return False
# Check if r = s + t
if r.startswith(s):
if r.endswith(t):
return True
# Check if r = t + s
if r.startswith(t):
if r.endswith(s):
return True
return False
# Test the function
s = "world"
t = "hello"
r = "helloworld"
print(solve(s, t, r))
True
Alternative Approach
We can also solve this problem using direct string comparison ?
def check_concatenation(s, t, r):
return r == s + t or r == t + s
# Test with multiple examples
test_cases = [
("world", "hello", "helloworld"),
("world", "hello", "worldhello"),
("abc", "def", "abcdef"),
("abc", "def", "defabc"),
("abc", "def", "abcde") # This should return False
]
for s, t, r in test_cases:
result = check_concatenation(s, t, r)
print(f"s='{s}', t='{t}', r='{r}' ? {result}")
s='world', t='hello', r='helloworld' ? True s='world', t='hello', r='worldhello' ? True s='abc', t='def', r='abcdef' ? True s='abc', t='def', r='defabc' ? True s='abc', t='def', r='abcde' ? False
Performance Comparison
| Method | Time Complexity | Space Complexity | Advantage |
|---|---|---|---|
| String slicing approach | O(n) | O(1) | More efficient for long strings |
| Direct concatenation | O(n) | O(n) | Simpler and more readable |
Conclusion
Both approaches effectively solve the concatenation problem. Use the string slicing method for better memory efficiency, or the direct concatenation approach for cleaner, more readable code.
Advertisements
