Open In App

Python Set | Pairs of complete strings in two sets

Last Updated : 21 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Two strings are said to be complete if on concatenation, they contain all the 26 English alphabets. For example, “abcdefghi” and “jklmnopqrstuvwxyz” are complete as they together have all characters from ‘a’ to ‘z’. We are given two sets of sizes n and m respectively and we need to find the number of pairs that are complete on concatenating each string from set 1 to each string from set 2. Examples:

Input : set1[] = {"abcdefgh", "geeksforgeeks",
                 "lmnopqrst", "abc"}
        set2[] = {"ijklmnopqrstuvwxyz", 
                 "abcdefghijklmnopqrstuvwxyz", 
                 "defghijklmnopqrstuvwxyz"} 
Output : 7
The total complete pairs that are forming are:
"abcdefghijklmnopqrstuvwxyz"
"abcdefghabcdefghijklmnopqrstuvwxyz"
"abcdefghdefghijklmnopqrstuvwxyz"
"geeksforgeeksabcdefghijklmnopqrstuvwxyz"
"lmnopqrstabcdefghijklmnopqrstuvwxyz"
"abcabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyz"

We have existing solution for this problem please refer Pairs of complete strings in two sets of strings link. We can solve this problem quickly in python using Set data structure. Approach is very simple,

  1. Consider all pairs of strings, concatenate them one by one and converts it into set.
  2. Now one by one add all alphabets in concatenated string into set. Since set contains unique values so if length of set is equal to 26 that means set contains all 26 english alphabets.

Python3




# Function to find pairs of complete strings
# in two sets of strings
   
def completePair(set1,set2):
       
    # consider all pairs of string from
    # set1 and set2
    count = 0
    for str1 in set1:
        for str2 in set2:
            result = str1 + str2
   
            # push all alphabets of concatenated 
            # string into temporary set
            tmpSet = set([ch for ch in result if (ord(ch)>=ord('a') and ord(ch)<=ord('z'))])
            if len(tmpSet)==26:
                count = count + 1
    print (count)
   
# Driver program
if __name__ == "__main__":
    set1 = ['abcdefgh', 'geeksforgeeks','lmnopqrst', 'abc']
    set2 = ['ijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyz']
    completePair(set1,set2)


Output

7

Time complexity: O(n^2 * m). 
Auxiliary space: O(1).



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads