Python – Disjoint Strings across Lists

When we need to find pairs of strings from two lists that share no common characters, we use disjoint string analysis. Two strings are disjoint if they have no characters in common.

Understanding Disjoint Strings

Disjoint strings are strings that don't share any common characters. For example, "fun" and "its" are disjoint because they have no letters in common.

Example

Here's how to find all disjoint string pairs from two lists ?

from functools import reduce

def determine_disjoint_pairs(disjoint_data, my_result=[]):
    if not disjoint_data and not reduce(lambda a, b: set(a) & set(b), my_result):
        yield tuple(my_result)
    
    elif disjoint_data:
        for k in disjoint_data[0]:
            yield from determine_disjoint_pairs(disjoint_data[1:], my_result + [k])

list_1 = ["python", "is", "fun"]
list_2 = ["its", "awesome", "learning"]

print("The first list is :")
print(list_1)
print("The second list is :")
print(list_2)

result = list(determine_disjoint_pairs([list_1, list_2]))

print("The disjoint string pairs are :")
print(result)
The first list is :
['python', 'is', 'fun']
The second list is :
['its', 'awesome', 'learning']
The disjoint string pairs are :
[('fun', 'its'), ('fun', 'awesome')]

How It Works

The function uses recursion to check all possible combinations:

  • Base case: When no more lists to process, check if current pair is disjoint using set intersection
  • Recursive case: Try each string from the first list with remaining lists
  • Disjoint check: Uses set(a) & set(b) to find common characters

Simpler Approach

Here's a more readable version using nested loops ?

def find_disjoint_pairs(list1, list2):
    disjoint_pairs = []
    
    for str1 in list1:
        for str2 in list2:
            # Check if strings share no common characters
            if not set(str1) & set(str2):
                disjoint_pairs.append((str1, str2))
    
    return disjoint_pairs

list_1 = ["python", "is", "fun"]
list_2 = ["its", "awesome", "learning"]

pairs = find_disjoint_pairs(list_1, list_2)
print("Disjoint pairs:", pairs)
Disjoint pairs: [('fun', 'its'), ('fun', 'awesome')]

Why These Pairs Are Disjoint

# Let's check why "fun" and "its" are disjoint
str1, str2 = "fun", "its"

set1 = set(str1)
set2 = set(str2) 

print(f"Characters in '{str1}': {set1}")
print(f"Characters in '{str2}': {set2}")
print(f"Common characters: {set1 & set2}")
print(f"Are disjoint: {len(set1 & set2) == 0}")
Characters in 'fun': {'u', 'f', 'n'}
Characters in 'its': {'s', 't', 'i'}
Common characters: set()
Are disjoint: True

Conclusion

Disjoint strings share no common characters. Use set intersection to check if two strings are disjoint, and iterate through all combinations to find disjoint pairs across lists.

Updated on: 2026-03-26T01:00:21+05:30

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements