Learner Level

Implement the singleNumberUsingXor method that returns the number that appears once using XOR logic.

The input array nums contains integers where every value appears exactly twice except one value that appears only once.

Your task is to return the value that appears once.

For example, in [4,1,2,1,2], the duplicate values cancel out and the single value is 4.

Example 1

Input
nums (int[]) = [4,1,2,1,2]
size (int) = 5
Returns (int) 4

Example 2

Input
nums (int[]) = [2,2,1]
size (int) = 3
Returns (int) 1

Example 3

Input
nums (int[]) = [1]
size (int) = 1
Returns (int) 1

Use the XOR operator.

XOR has a useful property: x XOR x = 0 and x XOR 0 = x. So when all numbers are XORed together, pairs of equal numbers become zero and the only remaining value is the single number.

This solves the problem in one pass without using extra storage.

Pseudocode:

function singleNumberUsingXor(nums, size):
    result = 0
    for i from 0 to size - 1:
        result = result XOR nums[i]
    return result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.