
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recover and Decode XORed Array in Python
Suppose we have a hidden array arr with n non-negative integers. Now this array is encoded into another array enc of length n-1. So here enc[i] = arr[i] XOR arr[i+1]. If we have the encoded enc array and an integer first, that is the first element of actual array, we have to find 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].
To solve this, we will follow these steps −
arr := an array with only one element first
-
for i in range 0 to size of enc - 1, do
insert arr[i] XOR enc[i] at the end of arr
return arr
Example (Python)
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 print(solve(enc, first))
Input
[8,3,2,7], 4
Output
[4, 12, 15, 13, 10]
Advertisements