logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›arrays›logic building

Missing Number

# Question

Given an array nums containing nnn distinct numbers chosen strictly from the range [0,n][0, n][0,n], find and return the single number that is missing from the sequence. The execution must run in O(n)O(n)O(n) time and use O(1)O(1)O(1) auxiliary space.

# Solution

# Pattern

Bitwise XOR Cancellation This approach leverages the self-inverting property of the exclusive-OR logic gate: X⊕X=0X \oplus X = 0X⊕X=0 and X⊕0=XX \oplus 0 = XX⊕0=X. By XORing the input set against the complete range sequence, all present numbers cancel out, isolating the single missing entry.

# How to Identify

  • The input elements are bound within a highly strict sequential index envelope (000 to nnn).
  • The problem mandates an exhaustive search for a single missing, duplicated, or altered item.
  • Rigid space bounds (O(1)O(1)O(1) memory) prevent the use of secondary tracking buffers like sets or hash tables.

# Description

Step-by-step explanation:

  • Step 1: Set Base State. Initialize an integer tracking register xorSum to the value nnn (the length of the array). This accounts for the upper bound element of the range [0,n][0, n][0,n] since the tracking loop will only step through indexes up to n−1n-1n−1.
  • Step 2: Linear Stream Scan. Run a linear scan through the input collection from index i=0i = 0i=0 to n−1n-1n−1.
  • Step 3: Bitwise Masking. At every single item iteration, update your tracking register by XORing it with both the current loop index counter iii and the value stored at that index location nums[i]: xorSum=xorSum⊕i⊕nums[i]\text{xorSum} = \text{xorSum} \oplus i \oplus \text{nums}[i]xorSum=xorSum⊕i⊕nums[i]
  • Step 4: Return Isolated Value. Upon loop termination, every number that appeared as both an index position and an array entry will have self-destructed into a value of 000. The value remaining in xorSum is the missing element.

# The Intuition

Think of this solution as an automated Inventory Audit Registry.

Imagine you are handed a manufacturing manifest containing a list of uniquely stamped parts ranging from 000 to nnn (represented by your loop index counters plus the base offset nnn). You are also handed a physical storage crate containing these parts, but one item is missing (represented by the values inside nums).

Instead of counting or adding their weights up to massive amounts, you pick up a manifest item and a crate item simultaneously and clash them together. If they match, they cancel out and vanish from your workspace. Because your tracking variable processes every index alongside every value, every matched pair annihilates itself. The unique item that fails to find a twin never gets canceled out and is left standing alone at the end.

# Complexity

LabelWorstAverage
Time ComplexityO(n)O(n)O(n)O(n)O(n)O(n)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

O(n)O(n)O(n). The sequence is parsed exactly once via a single-pass loop layout. Every element triggers low-level bit operations that run in constant time.

# Space Complexity

O(1)O(1)O(1). The internal memory allocation requires only a single scalar primitive variable, completely independent of input scaling.

# Code

class Solution {
    /**
     * Finds the missing number using bitwise XOR to enforce 32-bit type safety.
     * Time Complexity: O(n)
     * Space Complexity: O(1)
     */
    public int missingNumber(int[] nums) {
        int n = nums.length;
        
        // Seed with 'n' because the loop indices will only span from 0 to n-1
        int xorSum = n;
        
        // Accumulate cancellations across all index-value pairings
        for (int i = 0; i < n; i++) {
            xorSum ^= i ^ nums[i];
        }
        
        return xorSum;
    }
}

# Caveats

  • Unordered Constraints Only: This linear approach is independent of ordering. However, if the interviewer states the array is already sorted, a linear pass is sub-optimal; you should transition to a Binary Search approach to locate the index mismatch in O(log⁡n)O(\log n)O(logn) time.
  • Strict Boundary Bounds: The properties of this bitwise cancellation model depend on values matching the range [0,n][0, n][0,n]. If any element violates this boundary, the cancellation mechanics break completely.

# Concepts to Think About

  • Algebraic Formula Bounds: While n(n+1)2\frac{n(n+1)}{2}2n(n+1)​ works conceptually, implementing it using standard 32-bit integers risk overflow at n≥46,341n \ge 46,341n≥46,341, necessitating a 64-bit long conversion.
  • XOR Algebraic Properties: Bitwise exclusive-OR operations are fully commutative (A⊕B=B⊕AA \oplus B = B \oplus AA⊕B=B⊕A) and associative (A⊕(B⊕C)=(A⊕B)⊕CA \oplus (B \oplus C) = (A \oplus B) \oplus CA⊕(B⊕C)=(A⊕B)⊕C).
  • Cyclic Sort Placement: If array modification is permitted, swapping elements into their literal matching indices (nums[i] == i) isolates missing values without tracking calculations.
  • In-Place Read Immutability: Unlike mutating sort operations, the bitwise XOR framework treats the underlying collection as read-only, ensuring complete thread safety.
  • Cyclic Sort: This problem can also be solved using the Cyclic Sort pattern, where you try to place every number i at nums[i]. After sorting, the first index i where nums[i] != i is your missing number. When would you prefer this over the Math approach?
  • Multiple Missing Numbers: If the array was missing two numbers, would the Sum method still work? (Hint: You would need a second equation, like the sum of squares, to solve for two variables).
  • Binary Search: If the input array was sorted, could you find the missing number faster than O(n)? (Hint: Look for the first index i where `nums[i] != i$ using Binary Search).

# Logical Follow-up

Question: What if the sequence spans from 111 to n+1n+1n+1 instead of 000 to nnn? Solution: Initialize xorSum = 0 and process the loop indices as i + 1 inside your XOR expression to match the value structure.

Question: What if two distinct numbers are missing from the array instead of one? Solution: A single XOR pass over the combined elements and indices will yield a value equal to X⊕YX \oplus YX⊕Y (the XOR of the two missing numbers). Find the rightmost set bit in this result to establish a dividing line. Run a second pass, separating numbers and indices into two distinct groups based on whether that specific bit is set or clear. Each pool will isolate one of the missing values.

PreviousSingle NumberNextIntersection of Two Sorted Arrays (with Duplicates)
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up