Given a String, check if it’s present in order in the character list and vice versa.
Input : test_str = ‘geeks’, K = [‘g’, ‘e’, ‘e’, ‘k’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’] [ String in Character list ]
Output : True
Explanation : geeks is present in list , starting from 7th index till end.
Input : test_str = ‘geeksforgeeks’, K = [‘g’, ‘e’, ‘e’, ‘k’, ‘s’] [Character list in String]
Output : True
Explanation : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’] present in string, starting from the beginning of string.
Method #1: Using in operator + join() [ String in character list ]
In this, we convert the character list to a string using join() and apply it in the operator to test for substring presence.
Python3
test_str = 'geeks'
print ( "The original string is : " + str (test_str))
K = [ 'g' , 'e' , 'e' , 'k' , 'f' , 'o' , 'r' , 'g' , 'e' , 'e' , 'k' , 's' ]
joined_list = ''.join(K)
res = test_str in joined_list
print ( "Is String present in character list : " + str (res))
|
OutputThe original string is : geeks
Is String present in character list : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using in operator + join() [ Character List in String ]
In this, the target character list is converted to String and then checked in String using in operator.
Python3
test_str = 'geeksforgeeks'
print ( "The original string is : " + str (test_str))
K = [ 'g' , 'e' , 'e' , 'k' , 's' ]
joined_list = ''.join(K)
res = joined_list in test_str
print ( "Is character list present in String : " + str (res))
|
OutputThe original string is : geeksforgeeks
Is character list present in String : True
Time Complexity: O(n) -> as join method takes O(n) complexity
Auxiliary Space: O(n)
Method 3 : using the set() function and intersection() method
Step-by-step approach:
- Initialize the original string and print it.
- Initialize the character list.
- Convert the character list to a set using the set() function.
- Get the intersection of the character set and the set of the original string using the intersection() method.
- Check if the length of the intersection set is equal to the length of the character set.
- Print the result.
Python3
test_str = 'geeksforgeeks'
print ( "The original string is : " + str (test_str))
K = [ 'g' , 'e' , 'e' , 'k' , 's' ]
char_set = set (K)
intersect_set = char_set.intersection( set (test_str))
res = len (intersect_set) = = len (char_set)
print ( "Is character list present in String : " + str (res))
|
OutputThe original string is : geeksforgeeks
Is character list present in String : True
Time complexity: O(n), where n is the length of the original string.
Auxiliary space: O(k), where k is the length of the character list.