Given two strings S1 and S2 of length N and a positive integer K, the task is to find the lexicographically smallest string such that it differ from the given two strings S1 and S2 at exactly K places. If there is no such string exists then print “-1”.
Input: N = 4, K = 3, S1 = “ccbb”, S2 = “caab”
String “abcb” differs from S1 at exactly 3 places i.e., at positions 1, 2 and 3, and
String “abcb” differs from S2 at exactly 3 places i.e., at positions 1, 2 and 3.
Input: N = 5, K = 1, S1 = “cbabb”, S2 = “babaa”
No such string exists that simultaneously differs from S1 and S2 only at 1 position.
- Instead of building S3 from scratch, pick S2 as the resultant string S3 and try to modify it according to the given constraints.
- Find at how many positions does the answer string S3 differs from S1.
- Let they differ from each other at exactly d positions. Then the minimum number of places in which the answer string S3 can differ from both the string is ceil(d/2) and maximum number of places can be N.
- If K is within the range [ceil(d/2), N] then S3 exists otherwise S3 doesn’t exists and print “-1”.
- For string S3 below are the cases:
- K greater than d
- If K is greater than d then modify all the positions at which S1 differs from S3 such that after modification, S3 at that position will now differ from both S1 and S2. Decrement K.
- Modify the positions at which S1 is the same as S3 such that after modification, S3 at that position will now differ from both S1 and S2. Decrement K.
- K less than or equal to d
- In this case, only modify the S3 position at which S1 and S3 differ.
- After modification let X be the number of positions at which only S1 differs from S3 and S2 differs from S3.
- Let T be the number of positions which both S1 and S2 differ from S3. Then the equation’s will be:
(2 * X) + T = d
X + T = K
- Solving these equations, the values of X and T can be obtained and modify the answer string S3 accordingly.
- K greater than d
Below is the implementation of the above approach:
Time Complexity: O(N)