Decode XORed Array — LeetCode 1720 Python Solution
- Problem
- #1720
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1].
Example
- Input
- encoded = [1,2,3], first = 1
- Output
- [1,0,2,1]
- Explanation
- If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
Python solution
class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
ans = [first]
for x in encoded:
ans.append(ans[-1] ^ x)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the array auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1720. Decode XORed Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1720. Decode XORed Array?
- LeetCode 1720. Decode XORed Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1720. Decode XORed Array?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1720. Decode XORed Array?
- The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
- What topics does LeetCode 1720. Decode XORed Array cover?
- LeetCode 1720. Decode XORed Array is tagged Bit Manipulation and Array on LeetCode.