Python program to Check all strings are mutually disjoint
Last Updated :
18 Mar, 2023
Given a string list, our task is to write a Python Program to check all strings are disjoint from one another.
Example:
Input : test_list = ["gfg", "is", "bet"]
Output : True
Explanation : No string character repeat in other strings.
Input : test_list = ["gfg", "is", "best"]
Output : False
Explanation : s repeats in both "is" and "best", hence false.
Method #1 : Using any() + intersection() + enumerate()
In this, we perform the task of getting common elements using intersection(), and the intersection is performed between all combinations of strings with each other using enumerate() and any() is used to test if any string has any character present in other string.
Python3
# Python3 code to demonstrate working of
# Test if all strings are mutually disjoint
# Using any() + intersection() + enumerate()
# initializing list
test_list = ["gfg", "is", "bet"]
# printing original list
print("The original list is : " + str(test_list))
# performing intersection of each string with every other
res = not any(set(list(sub1)).intersection(set(list(sub2)))
for idx, sub1 in enumerate(test_list)
for sub2 in test_list[idx + 1:])
# printing result
print("Are strings mutually disjoint? : " + str(res))
Output:
The original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : True
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method #2 : Using join() + len() + set()
This problem can be solved by matching the concatenated string lengths and checking for equality of lengths of strings and converted set. Fails in case in which is similar string contains duplicate elements.
Python3
# Python3 code to demonstrate working of
# Test if all strings are mutually disjoint
# Using
# initializing list
test_list = ["gfg", "is", "bet"]
# printing original list
print("The original list is : " + str(test_list))
# performing concatenation and checking
# for lengths
concats = ''.join(test_list)
res = len(concats) == len(set(concats))
# printing result
print("Are strings mutually disjoint? : " + str(res))
Output:
The original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : False
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using Counter() function
Python3
# Python3 code to demonstrate working of
# Test if all strings are mutually disjoint
from collections import Counter
# initializing list
test_list = ["gfg", "is", "best"]
# printing original list
print("The original list is : " + str(test_list))
concats = ""
for i in test_list:
freq = Counter(i)
concats += ''.join(list(freq.keys()))
res = len(concats) == len(Counter(concats))
# printing result
print("Are strings mutually disjoint? : " + str(res))
OutputThe original list is : ['gfg', 'is', 'best']
Are strings mutually disjoint? : False
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using numpy unique()
Python3
import numpy as np
# initializing list
test_list = ["gfg", "is", "bet"]
# printing original list
print("The original list is : " + str(test_list))
# create array from list
arr = np.array(list("".join(test_list)))
# using numpy to get unique elements
# checking unique elements length and list length
res = len(np.unique(arr)) == len(arr)
# printing result
print("Are strings mutually disjoint? : " + str(res))
Output:
The original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using a nested loop and a flag variable
This method involves using two nested loops to compare each string with every other string in the list. A flag variable is used to keep track of whether there is any common character between two strings. If any two strings have a common character, the flag is set to True and the loops are broken. If the flag remains False, it means that all the strings are mutually disjoint.
Python3
# Python3 code to demonstrate working of
# Test if all strings are mutually disjoint
# Using nested loops and a flag variable
# initializing list
test_list = ["gfg", "is", "bet"]
# printing original list
print("The original list is : " + str(test_list))
# performing intersection of each string with every other
flag = False
for i in range(len(test_list)):
for j in range(i+1, len(test_list)):
if set(test_list[i]) & set(test_list[j]):
flag = True
break
if flag:
break
# printing result
print("Are strings mutually disjoint? : " + str(not flag))
OutputThe original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : True
Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(1), which is constant.
Method #6: Using Counter and sets
- Import the Counter class from the collections module.
- Define a test_list with some strings.
- Convert the list of strings into a single string using the join() method and assign the result to the joined variable.
- Create a Counter object from the joined string using the Counter() method and assign it to the char_count variable.
- Set a flag variable to False.
- Check if the length of the Counter object is equal to the length of the joined string. If they are equal, it means that all characters in the joined string are unique, so set the flag variable to True.
- Print the result of the flag variable, which will be True if the strings are mutually disjoint, and False otherwise.
Python3
from collections import Counter
test_list = ["gfg", "is", "bet"]
# printing original list
print("The original list is : " + str(test_list))
joined = "".join(test_list)
char_count = Counter(joined)
flag = False
if len(char_count) == len(joined):
flag = True
# printing result
print("Are strings mutually disjoint? : " + str(not flag))
#This code is contributed by Vinay Pinjala.
OutputThe original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : True
The time complexity of the algorithm is O(n), where n is the total number of characters in all the strings in the input list. This is because the join() method takes O(n) time to concatenate all the strings in the list into a single string, and creating a Counter object from the joined string takes O(n) time as well. The loop that checks the length of the Counter object takes O(1) time.
The auxiliary space of the algorithm is also O(n), where n is the total number of characters in all the strings in the input list. This is because the joined string and the Counter object both require O(n) space to store all the characters in the strings. The flag variable and other constant-sized variables used in the algorithm require O(1) space.
Similar Reads
Python Program to Join Equi-hierarchy Strings
Given a list of strings with several hierarchies, the task is to write a python program to join those which have the same hierarchies. Elements in the same dimension before a dimension change are known to be in the same hierarchy. Input : test_list = ["gfg ", " best ", [" for ", " all "], " all ", [
4 min read
Python Program To Check If A String Is Substring Of Another
Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :Â Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
3 min read
Python program to find String in a List
Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, weâll explore several methods to find a string in a list, starting from the most e
3 min read
Python program to check if a given string is Keyword or not
This article will explore how to check if a given string is a reserved keyword in Python. Using the keyword We can easily determine whether a string conflicts with Python's built-in syntax rules.Using iskeyword()The keyword module in Python provides a function iskeyword() to check if a string is a k
2 min read
Python program to Extract Mesh matching Strings
Given a character mesh, containing missing characters, match the string which matches the mesh. Example: Input : test_list = ["geeks", "best", "peeks"], mesh = "_ee_s" Output : ['geeks', 'peeks'] Explanation : Elements according to mesh are geeks and peeks. Input : test_list = ["geeks", "best", "tes
4 min read
Python Program to check for almost similar Strings
Given two strings, the task here is to write a python program that can test if they are almost similar. Similarity of strings is being checked on the criteria of frequency difference of each character which should be greater than a threshold here represented by K. Input : test_str1 = 'aabcdaa', test
5 min read
Python program to check a string for specific characters
Here, will check a string for a specific character using different methods using Python. In the below given example a string 's' and char array 'arr', the task is to write a python program to check string s for characters in char array arr. Examples: Input: s = @geeksforgeeks% arr[] = {'o','e','%'}O
4 min read
Check if Two Strings are Anagram - Python
The task of checking if two strings are anagrams in Python involves determining whether the two strings contain the same characters with the same frequency, but possibly in a different order. For example, given the strings "listen" and "silent", they are anagrams because both contain the same charac
2 min read
Python Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you
8 min read
Python program to check if given string is pangram
The task is to check if a string is a pangram which means it includes every letter of the English alphabet at least once. In this article, weâll look at different ways to check if the string contains all 26 letters.Using Bitmasking Bitmasking uses a number where each bit represents a letter in the a
2 min read