Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to recover decode XORed array in Python
Suppose we have a hidden array arr with n non-negative integers. This array is encoded into another array enc of length n-1, where enc[i] = arr[i] XOR arr[i+1]. Given the encoded array and the first element of the original array, we need to recover the original array.
So, if the input is like enc = [8,3,2,7], first = 4, then the output will be [4, 12, 15, 13, 10].
Algorithm
To solve this, we will follow these steps ?
arr:= an array with only one elementfirst-
for i in range 0 to size of enc - 1, do
insert
arr[i] XOR enc[i]at the end ofarr
return
arr
How It Works
Since enc[i] = arr[i] XOR arr[i+1], we can use the XOR property that A XOR B = C implies A XOR C = B. Therefore, arr[i] XOR enc[i] = arr[i+1].
Example
Let us see the following implementation to get better understanding ?
def solve(enc, first):
arr = [first]
for i in range(0, len(enc)):
arr.append(arr[i] ^ enc[i])
return arr
enc = [8, 3, 2, 7]
first = 4
result = solve(enc, first)
print("Original array:", result)
The output of the above code is ?
Original array: [4, 12, 15, 13, 10]
Step-by-Step Execution
Here's how the algorithm works step by step ?
def solve_with_steps(enc, first):
arr = [first]
print(f"Step 0: arr = {arr}")
for i in range(len(enc)):
next_val = arr[i] ^ enc[i]
arr.append(next_val)
print(f"Step {i+1}: arr[{i}] ^ enc[{i}] = {arr[i]} ^ {enc[i]} = {next_val}")
print(f" arr = {arr}")
return arr
enc = [8, 3, 2, 7]
first = 4
result = solve_with_steps(enc, first)
Step 0: arr = [4]
Step 1: arr[0] ^ enc[0] = 4 ^ 8 = 12
arr = [4, 12]
Step 2: arr[1] ^ enc[1] = 12 ^ 3 = 15
arr = [4, 12, 15]
Step 3: arr[2] ^ enc[2] = 15 ^ 2 = 13
arr = [4, 12, 15, 13]
Step 4: arr[3] ^ enc[3] = 13 ^ 7 = 10
arr = [4, 12, 15, 13, 10]
Conclusion
The XOR decoding algorithm leverages the property that XOR is its own inverse. Given the first element and encoded array, we can recover each subsequent element by XORing the previous element with the corresponding encoded value.
