Problem 1734

Abstract / Summary

Given an encoded array and the first element, reconstruct the original array using xor operations to undo the encoding.

Note

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

Python 1734.py

class Solution:
    def decode(self, encoded: List[int]) -> List[int]:
        # this is a pure math problem, not a programming problem
        size = len(encoded) + 1

        # XOR of 1...size
        all  = reduce(lambda a, b: a ^ b, range(1, size + 1))

        # encoded is: a^b, b^c, c^d, d^e, e^f, f^g, ... so that each value appears twice
        # except for the first and the last value
        # skipping every odd element/pair of encoded, each value appears only once:
        #             a^b,      c^d,      e^f, ...
        have = reduce(lambda a, b: a ^ b, encoded[::2])       # XOR of encoded
        # the only missing element is the final number
        # (it took me some time to note that n is always odd, so encoded has always an even length)
        result = [ all ^ have ]
        # now we have all we need and
        # let's build the whole result in reverse
        while encoded:
            result.append(result[-1] ^ encoded.pop())

        return reversed(result)
22 lines | 1018 bytes | submitted March 11, 2024 | GitHub   122% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (30k+ 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 provided Solution class implements a method decode that reconstructs the original integer sequence from an encoded list where each element is the XOR of two consecutive numbers in the original sequence. The algorithm relies on properties of the XOR operation to recover the missing values without explicit iteration over all possible combinations. The implementation proceeds in three conceptual phases: computing the total XOR of the full range, extracting a partial XOR from the encoded data, and iteratively rebuilding the original sequence in reverse order.

Key Steps

Determining the size of the original sequence

size = len(encoded) + 1

The length of the original array is one greater than the length of the encoded array because each encoded element represents a pair of adjacent numbers.

Computing the XOR of the complete range 1 … size

all = reduce(lambda a, b: a ^ b, range(1, size + 1))

By XOR-ing every integer from 1 to size, the variable all holds the cumulative XOR of all numbers that should appear in the final result.

Extracting the XOR of every second encoded element

have = reduce(lambda a, b: a ^ b, encoded[::2])

The encoded list follows the pattern a^b, b^c, c^d, …. Selecting every element at an even index (encoded[::2]) yields a subset where each original number, except the last, appears exactly once. XOR-ing this subset produces have, the partial XOR that is missing the final element of the original sequence.

Isolating the last element of the original sequence

result = [all ^ have]

Since all contains the XOR of the entire original sequence and have contains the XOR of all but the last element, XOR-ing them together yields the missing final number. This value becomes the first entry in the result list, which will later be extended in reverse order.

Reconstructing the full sequence in reverse

while encoded:
    result.append(result[-1] ^ encoded.pop())

The loop repeatedly removes the last element from encoded and XOR-s it with the most recently recovered number (result[-1]). Because each encoded entry is the XOR of two consecutive original numbers, this operation reveals the preceding number. The process continues until the encoded list is exhausted, resulting in result containing the original sequence in reverse order.

Returning the correctly ordered sequence

return reversed(result)

The built-up list is reversed to present the original ordering before being returned to the caller.

Edge Cases Handled

The algorithm implicitly accommodates the situation where the encoded list is empty. In that case size becomes 1, all evaluates to the XOR of the single integer 1, and have reduces over an empty slice, yielding the identity element for XOR (0). Consequently result is initialized with [1], the loop body is skipped, and the method returns an iterator over a single-element list, correctly representing the original sequence.

Another subtle edge condition is the requirement that the length of encoded be even, which follows from the problem statement that the original sequence length is odd. The slicing operation encoded[::2] safely produces an empty list when encoded has length zero, and the while loop terminates cleanly when encoded becomes empty, ensuring no out-of-range accesses.

Performance Optimizations

The implementation leverages the associative and commutative properties of XOR to collapse multiple operations into single reductions. By using reduce with a lambda that performs XOR, the code computes the cumulative XOR of a range and a slice in linear time without auxiliary data structures. The choice to rebuild the result in reverse order eliminates the need for index calculations or additional temporary storage; each iteration appends a newly derived element directly to the list. The use of pop() on the original encoded list provides an O(1) removal from the end, keeping the loop efficient. Finally, returning a lazy reversed iterator avoids copying the list again, delivering the result with minimal overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a secret line of friends holding numbered cards. Each friend has a card, but instead of showing you the number, they show you the result of a little game called XOR played with the friend next to them. XOR is just a special way of mixing two numbers together.

The code starts by figuring out how many friends are standing in line because it knows the total amount of numbers that were used. There is a magical property where if you XOR all the possible numbers together and then XOR them with some of the hidden clues, one of the secrets pops out. That secret is the very last friend in the line.

Once that last number is found, the code works backward. Since it knows the secret clue between the last friend and the friend just before them, it can use that clue to discover the previous friend's number. It repeats this pattern, hopping backward through the line until every single friend's number is revealed. By the time it reaches the front, the entire mystery of the hidden numbers is solved.

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 = 7 | μ = 6.59 | σ = 1.52

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 C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
24 links | 14 authors | 7 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   March 11, 2024

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