Skip to content

1720. Decode XORed Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  vector<int> decode(vector<int>& encoded, int first) {
    vector<int> ans(encoded.size() + 1);
    ans[0] = first;

    for (int i = 0; i < encoded.size(); ++i)
      ans[i + 1] = ans[i] ^ encoded[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int[] decode(int[] encoded, int first) {
    int[] ans = new int[encoded.length + 1];
    ans[0] = first;

    for (int i = 0; i < encoded.length; ++i)
      ans[i + 1] = ans[i] ^ encoded[i];

    return ans;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def decode(self, encoded: list[int], first: int) -> list[int]:
    ans = [first]

    for e in encoded:
      ans.append(e ^ ans[-1])

    return ans