1790. Check if One String Swap Can Make Strings Equal
Approach
Collect differing indices; must be 0 (equal) or exactly 2 with cross-match chars.
Key Techniques
Hash tables provide O(1) average-case lookup, insert, and delete. They are the go-to tool for counting frequencies, detecting complements (Two Sum pattern), and caching seen values. In C#, use Dictionary<K,V> for maps and HashSet<T> for membership checks.
String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.
Counting problems enumerate valid configurations without explicitly generating them. Techniques: combinatorics (nCr), inclusion-exclusion, digit DP, and contribution of each element. In C#, use long to avoid overflow when multiplying counts.
// Approach: Collect differing indices; must be 0 (equal) or exactly 2 with cross-match chars.
// Time: O(n) Space: O(1)
public class Solution
{
public bool AreAlmostEqual(string s1, string s2)
{
List<int> diffIndices = new List<int>();
for (int i = 0; i < s1.Length; ++i)
{
if (s1[i] != s2[i])
diffIndices.Add(i);
}
return diffIndices.Count == 0 ||
(diffIndices.Count == 2 &&
s1[diffIndices[0]] == s2[diffIndices[1]] &&
s1[diffIndices[1]] == s2[diffIndices[0]]);
}
}