Reconstruct original string from resultant string based on given encoding technique
A binary string S of length N is constructed from a string P of N characters and an integer X. The choice of the ith character of S is as follows:
- If the character Pi-X exists and is equal to 1, then Si is 1
- if the character Pi+X exists and is equal to 1, then Si is 1
- if both of the aforementioned conditions are false, then Si is 0.
Given the resulting string S and the integer X, reconstruct the original string P. If no string P can produce the string S, output -1.
Input: S = “10011”, X = 2
Explanation: The input string S = “10011” can be constructed from the output string P = “01100”.
Input: S = “11101100111”, X = 3
Explanation: The input string S = “11101100111” cannot be constructed from any output string P.
Approach: The task can be solved by taking an auxiliary string with all 1s. Follow the below steps to solve the problem:
- Initialize the string P with all the characters as ‘1’.
- Now traverse the string S using a loop and put zeroes at the correct positions in P according to the given conditions:
- If S[i] is equal to ‘0’ and P[i-X] exists, i, e, (i-X)>=0, then put P[i-X] = ‘0’.
- If S[i] is equal to ‘0’ and P[i+X] exists, i.e, (i+X)<N, then put P[i+X] = ‘0’.
- Initialize a variable flag = 1 to determine whether the string P exists or not.
- To check for the correctness of the constructed string P, traverse the string S using a for loop:
- If S[i]==’1′ and either P[i-X] or P[i+X] exists and is equal to ‘1’, then the string P is so far correct and the traversal can continue.
- If S[i]==’1′ and either P[i-X] or P[i+X] does not exist or is not equal to 1, then set flag = 0, output -1 and break from the loop.
- If the flag is equal to 0 after the traversal of the string S, then output the original string P.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)