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 r equals the sum of lengths of s and t
  • If r starts with s, check if it ends with t
  • If r starts with t, check if it ends with s
  • Return True if either condition is satisfied, otherwise return False

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.

Updated on: 2026-03-25T14:35:36+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements