Check if One String Swap Can Make Strings Equal
LeetCode 1915 | Difficulty: Easyβ
EasyProblem Descriptionβ
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Example 1:
Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".
Example 2:
Input: s1 = "attack", s2 = "defend"
Output: false
Explanation: It is impossible to make them equal with one string swap.
Example 3:
Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: The two strings are already equal, so no string swap operation is required.
Constraints:
- `1 <= s1.length, s2.length <= 100`
- `s1.length == s2.length`
- `s1` and `s2` consist of only lowercase English letters.
Topics: Hash Table, String, Counting
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 151 ms)β
| Metric | Value |
|---|---|
| Runtime | 151 ms |
| Memory | 36.4 MB |
| Date | 2022-01-03 |
public class Solution {
public bool AreAlmostEqual(string s1, string s2) {
if(s1.Length != s2.Length) return false;
int k=0, l = 0, count = 0;
for(int i=0;i<s1.Length;i++)
{
if(s1[i] != s2[i])
{
if(count == 0)
{
k=i;
}
else if (count==1)
{
l=i;
}
else return false;
count++;
}
}
if(s1[k] == s2[l] && s1[l] == s2[k])
{
return true;
}
return false;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Hash map gives O(1) lookup β think about what to use as key vs value.
- LeetCode provides 2 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2.
Hint 2: Check that these positions have the same set of characters.