Luogu P1469 Chopsticks Solution: Find the Unpaired Value with XOR in O(n) Time and O(1) Space

This article explains Luogu P1469 Chopsticks: among an odd number of chopstick lengths, every value appears in pairs except one. The goal is to find the unpaired value under strict memory limits. The core solution uses streaming bitwise XOR accumulation, which avoids sorting and frequency counting arrays. Keywords: bitwise XOR, constant space, Luogu solution.

Technical Specifications at a Glance

Parameter Description
Problem Luogu P1469 Chopsticks
Language C++
Core Algorithm Bitwise XOR
Time Complexity O(n)
Extra Space Complexity O(1)
Input Size n ≤ 10^7 + 1
Value Range 1 ≤ ai ≤ 10^9
Memory Limit 8 MB
Platform / Protocol Online Judge / Standard Input and Output
Star Count Not provided in the source data
Core Dependencies iostream, standard C++ runtime

This problem is fundamentally a “single odd-occurrence element” problem

The problem gives you n chopstick lengths. Only one length appears once, while every other length appears exactly twice. The goal is not to pair them explicitly, but to directly compute the value that failed to find a match.

When the input size reaches 10^7, sorting introduces significant time overhead. If you use a hash table to count frequencies, you may run into the 8 MB memory limit. So the real challenge is not to “spot a pattern,” but to choose a data structure and operation that support streaming processing.

Bitwise XOR matches the problem requirements perfectly

XOR has two key properties: a number XOR itself becomes 0, and any number XOR 0 remains unchanged. In addition, XOR is commutative and associative, so the input order does not matter. Every paired value cancels out automatically.

The only remaining value is the length of the unpaired chopstick. That means you only need one accumulator variable and can compute the answer as you read the input, without storing the full dataset.

#include 
<iostream>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    int x;
    int ans = 0;

    cin >> n;
    while (n--) {
        cin >> x;
        ans ^= x; // Accumulate with XOR; paired elements cancel out automatically
    }

    cout << ans;
    return 0;
}

This code reads all lengths online and computes the unique unpaired chopstick length through cumulative XOR.

This solution satisfies both large-input and low-memory constraints

Many beginners first think of using an array to count occurrences, but here ai can be as large as 10^9, so you obviously cannot allocate buckets by value range. Even if you switch to map or unordered_map, you still introduce noticeable extra memory overhead.

The XOR solution only maintains a single integer ans, so the extra space usage stays constant. Under an 8 MB limit, this is almost the safest possible implementation.

Input efficiency is also an implicit test point

The original problem statement explicitly warns you to pay attention to input speed. Because n is large, using the default synchronized cin/cout may not be fast enough. Disabling synchronization and untying cin from cout is usually enough to pass this kind of problem.

ios::sync_with_stdio(false); // Disable synchronization with stdio to improve I/O performance
cin.tie(nullptr);            // Untie cin from cout to reduce unnecessary flushing

These two lines optimize standard input and output performance and are well suited for reading large volumes of integers.

The correctness follows directly from XOR algebra

Suppose all chopstick lengths are a1, a2, …, an, where only one value t appears once and every other value appears exactly twice. XOR all elements together:

// Logical expression sketch
result = a1 ^ a2 ^ ... ^ an; // XOR of all elements
// If a value k appears twice, then k ^ k = 0
// Therefore, all paired values disappear and only t remains

Because XOR is commutative and associative, you can reorder all paired terms arbitrarily and cancel them side by side. The final result is always t. This shows that the algorithm does not depend on input order and does not require sorting or preprocessing.

This illustrative code captures the core correctness argument: all paired lengths collapse to zero, leaving only the unique unpaired value.

The image on the original page can be reduced to contextual information

WeChat sharing prompt AI Visual Insight: This image is a sharing prompt animation from the CNBlogs page. It guides users to share the page through the UI, but it does not contain algorithm details, input/output specifications, or code execution results. It is only a page-level interaction element and does not affect understanding of the solution.

You should avoid two common mistakes in real submissions

First, do not read the sample data as one whole string. The original page contains formatting noise caused by backticks around the sample, but in an actual submission, you should read the input as a stream of integers.

Second, do not assume that “appears once” and broader “appears an odd number of times” variants can always be solved directly with the same approach. In this problem, every other element appears exactly twice, so XOR works immediately. If some values appear three times or five times, you need different bit-manipulation techniques.

A walkthrough of a minimal sample

// Input: 9
// 2 2 1 3 3 3 2 3 1
int ans = 0;
ans ^= 2; // 2
ans ^= 2; // 0
ans ^= 1; // 1
ans ^= 3; // 2
ans ^= 3; // 1
ans ^= 3; // 2
ans ^= 2; // 0
ans ^= 3; // 3
ans ^= 1; // 2

This walkthrough shows how all paired numbers cancel out step by step, leaving the final answer 2.

This is a classic introductory bit-manipulation problem

From a competitive programming perspective, the value of P1469 is not in implementation difficulty, but in training your ability to derive the algorithm from the constraints. Once you see huge input, tiny memory, and all other elements appearing in pairs, you should immediately think of XOR.

Problems like this also serve as the starting point for more advanced bit-manipulation tasks, such as “two numbers appear once” or “one number appears once while all others appear three times.” They all build on the same binary reasoning model.

FAQ

Q1: Why not sort the array to find the unpaired chopstick?

Sorting can indeed find the answer by comparing adjacent elements, but its time complexity is usually O(n log n). It also typically requires storing the full dataset, which increases memory usage. When n is huge and the memory limit is only 8 MB, XOR with O(n) time and O(1) space is a much better fit.

Q2: Why does XOR guarantee a correct answer?

Because identical numbers satisfy x ^ x = 0, and XOR is both commutative and associative. Every paired length cancels out completely. The only unpaired length cannot be canceled, so the final result must be the answer.

Q3: Can I use a hash table to count frequencies for this problem?

In theory, yes, but it is not recommended. A hash table must maintain extra structures for distinct lengths, so under large input sizes its memory pressure is much higher than the XOR approach. The memory limit is tight, so constant space is the optimal strategy.

[AI Readability Summary] This article reconstructs the solution to Luogu P1469 “Chopsticks.” The key idea is to use bitwise XOR to cancel paired elements and find the single unpaired chopstick length in O(n) time and O(1) extra space, which is ideal for large inputs under an 8 MB memory limit.