![]() |
VOOZH | about |
Given two strings, the task is to check whether these strings can be made equal by exactly one swap in any of the strings.
Examples:
Input: s1 = "geeks" , s2 = "keegs"
Output: True
Explanation: By just swapping 'k' and 'g' in any of string, both will become same.Input: s1 = "Converse", s2 = "Conserve"
Output: True
Explanation: By just swapping 'v' and 's' in any of string, both will become same.Input: s1 = "abc", s2 = "abc"
Output: False
Explanation: They are already same
Table of Content
The idea is to try all possible pairs of indices
(i, j)in one string and swap the characters at these positions. After each swap, compare the modified string with the second string. If they become equal, return true; otherwise, revert the swap and continue. If no swap makes the strings equal, return false.
true
Time Complexity: O(n^3)
Auxiliary Space: O(n)
The idea is to find exactly two mismatched positions in the strings and check if swapping them makes the strings identical. We iterate once, tracking mismatched indices using two variables. If there are exactly two mismatches and swapping them results in equality, return True; otherwise, return false.
true
Time Complexity: O(n)
Auxiliary Space: O(1)