Problem 1720

Abstract / Summary

Given a modified array where each element is xorred with a hidden value and the first element is missing find the original array using the given information.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1720.py

class Solution:
    def decode(self, encoded: List[int], first: int) -> List[int]:
        yield first
        for e in encoded:
            first ^= e
            yield first
6 lines | 182 bytes | submitted November 25, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 87% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The presented implementation defines a Solution class with a single method decode. The method receives an integer list encoded and an integer first. It produces the original array that was transformed into encoded by successive XOR operations. The method is written as a generator, yielding each element of the decoded sequence on demand rather than constructing a full list up front.

Key Steps

The first operation in the method is to emit the initial value supplied by the caller. This establishes the starting point for the reconstruction process.

yield first

The core of the algorithm is a loop that iterates over every element e in the encoded list. Inside the loop the current first value is updated by XOR-ing it with the current encoded element. The updated value represents the next element of the original array and is yielded immediately.

for e in encoded:
    first ^= e
    yield first

The use of the ^= operator modifies first in place, ensuring that the variable always holds the most recent decoded element. By yielding after each update, the method provides a lazy sequence that can be consumed incrementally.

Edge Cases Handled

When encoded is empty, the loop body is never executed. The generator still yields the initial first value, correctly representing an original array consisting of a single element. This behavior gracefully handles the minimal input size.

If encoded contains a single element, the loop runs exactly once. The XOR operation produces the second element of the original array, which is yielded after the initial element. The method therefore reconstructs a two-element array without any special branching.

The algorithm works for any integer values, including large positive numbers, zero, and negative numbers, because the XOR operator is defined for the full range of Python integers. No overflow concerns arise, as Python integers have arbitrary precision.

Performance Optimizations

The implementation processes the input in a single pass, updating the running value and emitting results on the fly. By using a generator (yield) rather than building an intermediate list, it avoids allocating additional memory proportional to the length of the input. This makes the method suitable for very large encoded sequences where memory consumption would otherwise be a limiting factor.

In-place modification of the first variable with the ^= operator eliminates the need for a temporary variable to hold the intermediate XOR result. This reduces the number of Python objects created during execution, contributing to lower overhead per iteration.

Overall, the design leverages Python’s iterator protocol to achieve a streamlined, memory-efficient reconstruction of the original array.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a row of secret number blocks. The first block is a special gift you already know. The other blocks are hidden inside mysterious boxes. To find the next number, you take the number you just discovered and play a little magic trick with it and the secret box. This magic trick is like a flip that changes the number. You keep doing this trick over and over, going down the line, until all the hidden numbers are revealed one by one. Once you finish flipping and discovering, you have a whole new line of numbers that were waiting to be found.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.74 | σ = 1.48

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python C++ Java TS
WalkCCC Python C++ Java
leetcode.ca Python C++ Java Go TS
Progiez Python C++ Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
29 links | 18 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

4 solutions   November 25, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality