Common Characters in Array of Strings

Find characters common to all strings.

AdvancedPhase 6 - Category 2: Array & String CombinationsExample 7 of 10
common-characters-in-array-of-strings.py
1# Take array of strings
2n = int(input("Enter number of strings: "))
3arr = []
4for i in range(n):
5 arr.append(input(f"String {i+1}: "))
6
7# Find common characters
8if arr:
9 common = set(arr[0])
10 for s in arr[1:]:
11 common = common & set(s)
12
13 print(f"Common characters: {sorted(common)}")
14else:
15 print("Array is empty")

Output

Enter number of strings: 3
String 1: hello
String 2: world
String 3: level
Common characters: ['e', 'l']

What's going on

Use set intersection to find common characters.

Key Concepts:

Convert each string to set
Use & operator for intersection
Find common characters