Open In App

Python - Filter Supersequence Strings

Last Updated : 27 Apr, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a Strings list and substring, the task is to write a Python program to extract all the strings that has all the characters that can be used to make a substring.

Examples:

Input : test_list = ["gfg", "/", "geeksforgeeks", "best", "for", "geeks"], substr = "kgs"
Output : ["geeksforgeeks", "geeks"]
Explanation : All kgs characters are present in both strings.
Input : test_list = ["gfg", "/", "geeksforgeeks", "best", "for", "geeks"], substr = "kgf"
Output : ["geeksforgeeks"]
Explanation : All kgs characters are present in only geeksforgeeks string.

Method 1 : Using all() + list comprehension

In this, we check for all the character presence in string using all(). The iteration of strings is done using list comprehension.


Output
The original list is : ['gfg', '/', 'geeksforgeeks', 'best', 'for', 'geeks']
Filtered strings : ['geeksforgeeks', 'geeks']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using filter() + all()

In this, we perform task of filtering using filter() and lambda function rather than list comprehension and conditionals used in upper method.


Output
The original list is : ['gfg', '/', 'geeksforgeeks', 'best', 'for', 'geeks']
Filtered strings : ['geeksforgeeks', 'geeks']

Time Complexity: O(n2) -> (for loop + in-built functions)
Auxiliary Space: O(n)

Method #3: Using set intersection

In this approach, we create sets of all characters of substring and each string of test_list and find the intersection of both sets
If the length of intersection is equal to the length of set of substring, it means all characters of substring are present in the string.


Output
The original list is : ['gfg', '/', 'geeksforgeeks', 'best', 'for', 'geeks']
Filtered strings : ['geeksforgeeks', 'geeks']

Time complexity: O(n), where n is the length of test_list
Auxiliary Space: O(n)

Method 4: Using for loop

Approach:

  1. Initialize the list and the substring as before.
  2. Create an empty list to store the filtered strings.
  3. Use a for loop to iterate through each string in the list.
  4. Check if all the characters in the substring are in the current string using the all() function and a generator expression.
  5. If all the characters are present, append the string to the result list.
  6. Print the result.

Output
Filtered strings : ['geeksforgeeks', 'geeks']

Time complexity: O(n * m), where n is the number of strings in the list and m is the length of the substring.
Auxiliary space: O(k), where k is the number of strings that meet the filtering criteria.


Next Article

Similar Reads