EASY NC#148 Blind #14 Bit Manipulation

268. Missing Number

๐Ÿ“– Problem

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Use XOR property: a ^ a = 0, a ^ 0 = a
  • โ†’ XOR all indices 0..n with all array values
  • โ†’ Duplicate numbers cancel out, leaving missing number
  • โ†’ Initialize result with n, then XOR with i and nums[i]
  • โ†’ Time: O(n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse XOR property: a ^ a = 0, a ^ 0 = a
  • โ€ขXOR all indices 0..n with all array values
  • โ€ขDuplicate numbers cancel out, leaving missing number

Common Pitfalls

  • โ€ขInitialize result with n, then XOR with i and nums[i]
  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
missingNumber([3,0,1]);
Expected:
2
Test Case 2
Not run
Input:
missingNumber([0,1]);
Expected:
2
Test Case 3
Not run
Input:
missingNumber([9,6,4,2,3,5,7,0,1]);
Expected:
8

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit