Similar Problems

Similar Problems not available

Check If One String Swap Can Make Strings Equal - Leetcode Solution

Companies:

LeetCode:  Check If One String Swap Can Make Strings Equal Leetcode Solution

Difficulty: Easy

Topics: string hash-table  

Problem Description:

Given two strings s1 and s2, you need to check if you can make the strings equal by swapping any two characters of s1.

Constraints:

  1. 1 <= s1.length, s2.length <= 100
  2. s1.length == s2.length
  3. s1 and s2 consist of only lowercase English letters.

Solution:

Approach:

The approach is to first check if the two given strings are equal. If they are equal, there is no need to swap any characters as they are already equal. If they are not equal, find the indices where the characters of s1 differ from s2. If there are more than two indices or the characters at these indices do not match when swapped, then it is not possible to swap the characters to make the string equal. If there are exactly two mismatching indices and swapping the characters at these indices makes the two strings equal, then the answer is "True" otherwise "False".

Algorithm:

  1. Define a boolean function called 'checkIfCanSwapStringsEqual' that takes two strings as input i.e., s1 and s2.
  2. Check if the two strings are equal.
    • If they are equal, return 'True' as it is not necessary to swap any characters as they are already equal.
  3. Create a list called 'different_indices' to store indices where s1 and s2 differ.
  4. Traverse both the strings s1 and s2 simultaneously using a for loop, and if any characters don't match, append the index of the character to the list 'different_indices'.
  5. Check if the length of 'different_indices' is greater than two, then it is not possible to swap any pair of characters to make the string equal, so return 'False'.
  6. If the length of 'different_indices' is two, then s1 and s2 can be made equal by swapping the characters at the indices stored in 'different_indices'.
  7. Check if the characters at the indices stored in 'different_indices' when swapped are equal to each other, then return 'True' otherwise 'False'.

Python code:

def checkIfCanSwapStringsEqual(s1: str, s2: str) -> bool: if s1 == s2: return True different_indices = [] for i in range(len(s1)): if s1[i] != s2[i]: different_indices.append(i) if len(different_indices) != 2: return False return s1[different_indices[0]] == s2[different_indices[1]] and s1[different_indices[1]] == s2[different_indices[0]]

Input: s1 = "abcd" s2 = "dcba"

Output: True

Explanation:

Here, we can swap the first and fourth characters of s1 to get "dcba" which is equal to s2.

Input: s1 = "abcde" s2 = "adcbe"

Output: False

Explanation:

Here, s1 and s2 differ at two indices i.e., 1 and 3, but swapping them doesn't give us the required output, hence the answer is 'False'.

Check If One String Swap Can Make Strings Equal Solution Code

1