Learner Level

Implement the missingNumberXorImportant method that finds the missing number using XOR logic.

The input array nums contains size distinct numbers taken from the range 0 to size.

Exactly one number from this range is missing. Your task is to find and return that missing number.

For example, if the array is [3,0,1] and size is 3, the full range should be 0,1,2,3. The missing number is 2.

Example 1

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

Example 2

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

Example 3

Input
nums (int[]) = [9,6,4,2,3,5,7,0,1]
size (int) = 9
Returns (int) 8

Use XOR to remove matching values.

XOR has a useful property: a number XORed with itself becomes 0, and a number XORed with 0 remains unchanged. XOR all numbers from 0 to size, then XOR all values present in the array.

All numbers that appear in both places cancel out. The only value left is the missing number.

Pseudocode:

function missingNumberXorImportant(nums, size):
    result = 0
    for i from 0 to size:
        result = result XOR i
    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.