VOOZH about

URL: https://www.geeksforgeeks.org/dsa/meta-strings-check-two-strings-can-become-swap-one-string/

⇱ Check if two strings can become same after one swap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if two strings can become same after one swap

Last Updated : 20 May, 2026

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

[Naive Approach] Using Brute Force - O(n^3) Time O(n) Space

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.


Output
true

Time Complexity: O(n^3)
Auxiliary Space: O(n)

[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space

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.


Output
true

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: