Leetcode 1790. Check if One String Swap Can Make Strings Equal
Given two strings s1
and s2
of equal length, return true
if you can swap two letters in s1
such that the result is equal to s2
; otherwise, return false
.
s1
and s2
are equal?
s1
makes it equal to s2
.false
output.false
(if they are not identical).public class Solution {
public boolean areAlmostEqual(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
int n = s1.length();
List<Integer> diff = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
diff.add(i);
}
}
// If there are no differences, the strings are already same
if (diff.size() == 0) {
return true;
}
// If there are exactly 2 differences, check if swapping them would make the strings equal
if (diff.size() == 2) {
int i = diff.get(0), j = diff.get(1);
return s1.charAt(i) == s2.charAt(j) && s1.charAt(j) == s2.charAt(i);
}
return false; // For any other number of differences
}
}
The time complexity of this solution is O(n) where n
is the length of the strings. This is because we only make a single pass through both strings to identify mismatched positions and perform constant-time checks.
The space complexity is O(1) for the auxiliary space used (ignoring the space used by the input strings themselves). The list diff
can only hold at most 2 indices, making its additional space usage constant.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?