Strings Differ by One Character - Problem
Given a list of strings dict where all strings have the same length, determine if there exist any two strings that differ by exactly one character at the same index position.
Your task is to return true if such a pair exists, otherwise return false.
Example: If you have strings ["abc", "axc", "def"], then "abc" and "axc" differ by only one character at index 1 (b vs x), so the answer would be true.
This problem is commonly asked in coding interviews and requires efficient string comparison techniques.
Input & Output
example_1.py โ Basic Case
$
Input:
["abc", "axc", "def"]
โบ
Output:
true
๐ก Note:
Strings 'abc' and 'axc' differ by exactly one character at index 1 (b vs x)
example_2.py โ No Match
$
Input:
["abc", "def", "ghi"]
โบ
Output:
false
๐ก Note:
No two strings differ by exactly one character. Each pair differs by 3 characters
example_3.py โ Multiple Differences
$
Input:
["abc", "axd", "def"]
โบ
Output:
false
๐ก Note:
The closest pair 'abc' and 'axd' differs by 2 characters (positions 1 and 2), not exactly 1
Visualization
Tap to expand
Understanding the Visualization
1
Create Fingerprints
For each password, create patterns by masking one character at a time
2
Check Database
Store each pattern in our security database
3
Detect Collision
If we encounter a pattern we've seen before, we found similar passwords
Key Takeaway
๐ฏ Key Insight: By creating masked patterns, we transform the problem from comparing strings directly to detecting pattern collisions in a hash table, making it much more efficient!
Time & Space Complexity
Time Complexity
O(n ร mยฒ)
n strings, m characters per string, m patterns per string to generate and hash
โ Linear Growth
Space Complexity
O(n ร m)
Hash set can store up to nรm patterns in worst case
โก Linearithmic Space
Constraints
- 1 โค dict.length โค 105
- 1 โค dict[i].length โค 300
- All strings in dict have the same length
- dict[i] consists of lowercase English letters only
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code