How does bit manipulation solve the missing number problem?
LeetCode Patterns Flashcards: Bit Manipulation, XOR Tricks, Masks, Powers of Two
Аудио-карточка · 0:30Nortren·
How does bit manipulation solve the missing number problem?
0:30
Given an array containing n distinct numbers from zero to n with one missing, XOR all array elements together and XOR with all numbers from zero to n. Every number that is present cancels out because it appears in both the array and the range, leaving only the missing number. This uses O of one space. Alternatively, calculate the expected sum of zero through n using the formula n times n plus one divided by two, subtract the actual array sum, and the difference is the missing number. Both approaches run in O of n time, but the XOR approach avoids potential integer overflow with large sums.
neetcode.io