MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Find Single Non-Duplicate Number with Explanation

C++ Hard Operators 36 views
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around appear, single, all. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

All numbers appear twice except one. Find that single number.
Real Life: Finding unique item in paired data.

Input Format

An integer n (size of array)
Then n integers
(All numbers appear twice except one number)

Output Format

The single number that appears only once.

Constraints

• n is odd

• Exactly one number appears once

• All other numbers appear twice

Concept Explanation

When a number appears twice, it cancels itself using XOR.
The number that appears once remains.

Step-by-Step Logic

1.Initialize result = 0.

2.Traverse the array from index 0 to n-1.

3.For each element arr[i]:

• Do result = result ^ arr[i].

4.Rules of XOR used:

5.x ^ x = 0

6.x ^ 0 = x

7.All paired numbers become 0.

8.The remaining value in result is the single number.

9.Print result.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
void operator_q13_single_number() { int arr[] = {4, 1, 2, 1, 2, 4, 7}; int size = 7; int result = 0; for(int i = 0; i < size; i++) { result = result ^ arr[i]; } cout << "Single non-duplicate number: " << result << endl; }

Output Example

Input:
5 2 3 2 4 3
Output:
4

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next