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
๐Ÿ” Password Similarity Detection SystemUser Passwords:secret123secret124Security Fingerprints:For 'secret123':*ecret123s*cret123se*ret123... and more๐Ÿ—„๏ธ Security Database*ecret123s*cret123se*ret123secre*123... more patterns ...For 'secret124':secre*124๐Ÿšจ PATTERN MATCH DETECTED!โš ๏ธ SECURITY ALERTSimilar passwords detected!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n ร— m)

Hash set can store up to nร—m patterns in worst case

n
2n
โšก 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
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22 Apple 15
28.5K Views
Medium-High Frequency
~18 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen