Given a lowercase string A of length N and an integer K, find the lexicographically smallest string B of the same length as A such that hamming distance between A and B is exactly K.
Input : A = "pqrs", k = 1. Output : aqrs We can differ by at most one character. So we put 'a' in the beginning to make the result lexicographically smallest. Input : A = "pqrs", k = 2. Output : aars
We start from left to right, if the character at the current position of string A is ‘a’, then we assign the current position of string B character ‘a’. This position will not contribute towards the hamming distance. If character at this position in A is not equal to ‘a’, then also we will assign current position of string B character ‘a’, now this will contribute towards hamming distance and this can be done at most k times because Hamming distance has to be equal to K, if this is already done K times, we will assign this position of B same character as A.
If after the previous step, hamming distance between A and B is K, we are done otherwise we have to make more changes to B. Now we will start from right to left in B, and if character at the current position is equal to the corresponding character of A, change character of B to ‘b’, hence increasing the hamming distance by one, we will do it until hamming distance becomes equal to K.
Below is the implementation of this approach:
This article is contributed by Anuj Chauhan. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string of length N and sum K
- Queries to answer the X-th smallest sub-string lexicographically
- Lexicographically smallest permutation of a string with given subsequences
- K-th lexicographically smallest unique substring of a given string
- Lexicographically smallest string formed by removing at most one character
- Lexicographically smallest string obtained after concatenating array
- Find the lexicographically smallest string which satisfies the given condition
- Swap all occurrences of two characters to get lexicographically smallest string
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Find the smallest window in a string containing all characters of another string
- Hamming Distance between two strings
- Reduce Hamming distance by swapping two characters