Given two strings S and T. Find the positions of two letters to be swapped in S so that the hamming distance between strings S and T is as small as possible.
Hamming Distance: Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters
Input : S = "permanent", T = "pergament" Output: 4 6 Input : S = "double" T = "bundle" Output : 4 1
Explanation 1 : Initially, the hamming distance between S and T is 2(at 4 and 6). After swapping the letters at positions 4 and 6 it becomes “pernament”. Here, the hamming distance is only 1. This is the minimum possible.
Explanation 2 : Before swapping: “double” “bundle”, distance = 4
After swapping: “boudle” “bundle”, distance = 2
In the given string, hamming distance can be decreased by at most two because, only two characters can be moved.
Case-I : Decrease distance by two is possible, if there are two positions with the same two letters in two strings but that appear in different order(like “bundle” and “double”).
Case-II : Decrease by one is possible by “fixing” the characters that are on wrong positions(like in “permanent” and “pergament”, here n stands in wrong pair with m and there is also unmatched m, which we can fix).
Case-III : If not possible to decrease the hamming distance, print -1.
Case-I : To decrease the distance by two, create a 2-d array dp[i][j](i is s – ‘a’ and j is t – ‘a’) and assign it to the index of i in string S. If repeated pair is found, print the corresponding indexes.
Case-II : To decrease the distance by one, maintain two arrays A and B
- Remove characters from the first string which are present in the second string
- Print list items containing all characters of a given word
- Find the smallest window in a string containing all characters of another string
- Length of the longest substring without repeating characters
- Print all permutations with repetition of characters
- Interleaving of two given strings with no common characters
- String matching where one string contains wildcard characters
- Find the first non-repeating character from a stream of characters
- Rearrange a string so that all same characters become d distance away
- Given a sorted dictionary of an alien language, find order of characters
- Find the longest substring with k unique characters in a given string
- Reverse a string without affecting special characters
- Check if edit distance between two strings is one
- Find all strings formed from characters mapped to digits of a number
- Rearrange a string so that all same characters become atleast d distance away
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.