Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Missing Number

Bit Manipulationeasy

Given `nums` containing `n` distinct numbers from the range `0..n`, implement `missingNumber(nums)` returning the one number missing.

Sample tests

Input: missingNumber([3,0,1])
Output: 2
Input: missingNumber([0,1])
Output: 2

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Summation also works but can overflow for very large n; XOR avoids that.

Learning resources

  • MDN: Bitwise operators
Approach & explanation (try first)

XOR-ing indices and values cancels present numbers, leaving the missing one. O(n) time, O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.