Check if given string can be formed by concatenating string elements of list in Python

We sometimes need to check if a required string can be formed from multiple strings present in a list. The order of strings in the list doesn't matter ? they can be concatenated in any sequence to form the target string.

Using Permutations

The itertools.permutations() function generates all possible combinations of strings in various orders. We check each combination by joining the strings until we find a match ?

from itertools import permutations

chk_str = 'balloon'
string_list = ['fly', 'on', 'o', 'hot', 'ball', 'air']

def can_form_string(target, strings):
    for i in range(2, len(strings) + 1):
        for perm in permutations(strings, i):
            if ''.join(perm) == target:
                return True
    return False

# Test the function
if can_form_string(chk_str, string_list):
    print("String can be formed.")
else:
    print("String cannot be formed.")
String can be formed.

How It Works

The function tries combinations of 2, 3, 4... up to all strings. For our example, it finds that 'ball' + 'o' + 'on' = 'balloon'.

Using Regular Expressions

The re module can create a pattern that matches any combination of the list strings. This approach uses a more compact regex pattern ?

import re

chk_str = 'balloon'
string_list = ['fly', 'on', 'o', 'hot', 'ball', 'air']

def can_form_string_regex(target, strings):
    pattern = "(?:" + "|".join(strings) + ")*$"
    regex = re.compile(pattern)
    return regex.match(target) is not None

# Test the function
if can_form_string_regex(chk_str, string_list):
    print("String can be formed.")
else:
    print("String cannot be formed.")
String can be formed.

Pattern Explanation

The regex pattern (?:fly|on|o|hot|ball|air)*$ matches any sequence of the list strings repeated zero or more times until the end of the target string.

Using Dynamic Programming (Optimized)

For better performance with longer strings, we can use dynamic programming to avoid redundant checks ?

def can_form_string_dp(target, strings):
    dp = [False] * (len(target) + 1)
    dp[0] = True  # Empty string can always be formed
    
    for i in range(1, len(target) + 1):
        for string in strings:
            if (i >= len(string) and 
                dp[i - len(string)] and 
                target[i - len(string):i] == string):
                dp[i] = True
                break
    
    return dp[len(target)]

# Test with the same example
chk_str = 'balloon'
string_list = ['fly', 'on', 'o', 'hot', 'ball', 'air']

if can_form_string_dp(chk_str, string_list):
    print("String can be formed.")
else:
    print("String cannot be formed.")
String can be formed.

Comparison

Method Time Complexity Best For
Permutations O(n! × m) Small lists
Regular Expressions O(2^n) Simple patterns
Dynamic Programming O(n × m × k) Long strings

Conclusion

Use permutations for small lists, regex for simple cases, and dynamic programming for optimal performance with longer strings. The DP approach is most efficient for large inputs.

Updated on: 2026-03-15T17:51:52+05:30

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements