Common Characters in Array of Strings
Find characters common to every string in a list. Students initialize a set from the first string and progressively intersect it with each later character set.
1# Take array of strings2n = int(input("Enter number of strings: "))3arr = []4for i in range(n):5 arr.append(input(f"String {i+1}: "))67# Find common characters8if arr:9 common = set(arr[0])10 for s in arr[1:]:11 common = common & set(s)1213 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: ['l']
In this one
- Intersect distinct character sets
- Apply an all-strings requirement
- Sort only the display
How it works
- 1
Initialize common from the first string's characters.
- 2
Intersect it with every later string's set.
- 3
Print sorted common characters, or the empty-array message.
Edge cases
What if one string is empty?
What if one string is empty?
The intersection becomes empty.
Are duplicate characters repeated in the result?
Are duplicate characters repeated in the result?
No. Sets keep distinct characters.
What's going on
common begins with distinct characters from arr[0]. Each intersection removes characters absent from the next string.
The final sorted set displays common characters once in predictable string order. Character frequencies are not preserved: one a in every string is enough regardless of repetitions. An empty list uses a message branch rather than indexing arr[0].
What if one string is empty? The intersection becomes empty.
Are duplicate characters repeated in the result? No. Sets keep distinct characters.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why intersect repeatedly?
Pick an answer to check it.
Question 2
What if one string is empty?
Pick an answer to check it.
Questions people ask
What if one string is empty?
The intersection becomes empty.
Are duplicate characters repeated in the result?
No. Sets keep distinct characters.
Why intersect repeatedly?
Every surviving character must occur in every string.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum