Quick revision
The short answer
This is a math and bits problem: we know exactly which values should be present, 1 to n. XOR every value from 1 to n with every value in the array, and each present value cancels itself, leaving only the missing one; the sum formula n(n + 1) / 2 minus the actual sum works too if computed in a long. Both take O(n) time and O(1) space.
The solution
What it costs
| Approach | Time | Extra space | Watch out for |
|---|---|---|---|
| Search for each candidate | O(n^2) | O(1) | slow for large n |
| Sort, then find the gap | O(n log n) | O(1) to O(n) | changes the array |
| Boolean seen array | O(n) | O(n) | memory |
| Sum formula in a long | O(n) | O(1) | overflow if done in int |
| XOR of expected and actual | O(n) | O(1) | nothing |
What to remember
We found the missing number by comparing the register with the room in a single number. The sum method subtracts the actual total from n(n + 1) / 2, computed in a long to avoid overflow. The XOR method XORs 1 to n with every array value, so each present value cancels and only the missing one is left. Both take O(n) time and O(1) space. The clue to remember is from 1 to n: when you know exactly what should be present, summarise expected and actual the same way and let them cancel.
1What the question asks, told as a class register
Think of a teacher taking the register. The register lists roll numbers 1 to 8, but only seven students are in the room today, sitting wherever they like. The teacher wants to know which roll number is absent. She does not need anyone's name or seat. She only needs to compare what should be there, the register, with what is there, the students.
Our problem is exactly that register. We are given an array of n - 1 numbers. They are distinct, which means no number appears twice, and each lies between 1 and n. Since there are n possible values and only n - 1 numbers, exactly one value from 1 to n is absent, and we must return it. The array can be in any order.
We will keep one example. The array is [3, 7, 1, 2, 8, 4, 5]. It has seven numbers, so n is 7 + 1 = 8, and the register is 1 to 8. Checking by hand, 1, 2, 3, 4 and 5 are present, 6 is not, and 7 and 8 are present, so the answer is 6. In the picture the top row is the register and the bottom row is the array we are given.
Top row: the values 1 to 8 that should be present. Bottom row: the array we are given, in its own order.
- array length
- 7
- n
- 7 + 1 = 8
- answer
- 6
1The bottom row holds seven of the eight values. The marked 6 in the top row has no match below it, so 6 is the missing number.
What to assume
- Are the values really distinct and inside 1 to n?
- We assume so, as promised.
- Is the array sorted?
- No, it can be in any order.
- Can it be empty?
- Yes, and then n is 1 and the missing number is 1.
- May we change the array?
- We assume not.
- And how large can n be?
- Perhaps a hundred thousand or more.
The good news is in the word exactly. Because we know precisely which numbers should be there, we do not have to discover the range or sort anything. We only need some quick way to compare the full register with the room, and there turn out to be two lovely ones, a sum and a trick with bits.
A careful candidate asks a few questions first. Are the values really distinct and inside 1 to n? We assume so, as promised. Is the array sorted? No, it can be in any order. Can it be empty? Yes, and then n is 1 and the missing number is 1. May we change the array? We assume not. And how large can n be? Perhaps a hundred thousand or more, which matters for one of our methods, as we will see.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a math and bits problem
Reading the question for the first time, most beginners reach for searching or sorting. Sort the array and walk along until a number is not one more than the one before it. Or take each value from 1 to n and look for it. Both work, and we will try the second honestly, but neither uses the strongest fact in the question.
So let us take the clues one at a time. The first clue is the phrase from 1 to n. It tells us the complete set of values in advance, before we look at the array. Whenever we know what a complete collection should contain, we can compute something about the whole collection without reading any data, such as its total.
The second clue is n - 1 distinct integers. Exactly one value is absent and nothing repeats. That means that the array is the full set with one value taken out. If we compute the same summary for the array and compare it with the summary of the full set, the difference can only come from the one value that was taken out.
Together the clues point to the math and bits pattern. Here the name means using a property of numbers, either ordinary arithmetic or the bits that store a number, instead of a data structure. The general rule to carry to new problems is this. When a problem tells you exactly which values should be present, summarise the expected set and the actual array in the same way, with a sum or with XOR, and let the present values cancel, so that only the missing or extra value is left.
Some patterns look similar but cost more. A hash set of the values answers the question in O(n) time but stores n numbers. Sorting and then finding the gap costs O(n log n). Binary search fits only when the array is already sorted, which it is not here. Arithmetic does the same job in one pass with a single number of memory.
3The honest first attempt, looking for each number
The honest first attempt is a perfectly good instinct. For each candidate from 1 to n, scan the array to see whether it is there, and return the first candidate that is not found. It is easy to believe, because it is the teacher reading each roll number aloud and looking around the room.
Let us count its work on the example. Looking for 1 takes 3 checks, because 1 is the third value. Looking for 2 takes 4, for 3 takes 1, for 4 takes 6, for 5 takes 7, and looking for 6 scans all 7 values and finds nothing. That is 28 checks before we can answer. For n values the scans can cost about n x n checks in the worst case, so the time is O(n^2), read as order n squared. The space is O(1), just a few variables.
Where is the waste? Each scan reads the whole array again to answer a yes or no question about one value, and then forgets what it saw. A natural middle step remembers: a boolean array called seen, of size n + 1, filled in one pass with seen[v] = true, and then a second pass over 1 to n to find the entry still false. That is O(n) time, but O(n) extra space. We are storing n separate facts when all we want at the end is one number.
4From the waste to letting the present numbers cancel
So the real question is whether one number can summarise which values are present well enough to reveal the missing one. Let us try the most familiar summary first, the total. The values 1 to n add up to n(n + 1) / 2, a formula you may remember from school. For n = 8 that is 8 x 9 / 2 = 36. The array adds up to 3 + 7 + 1 + 2 + 8 + 4 + 5 = 30. The difference, 36 - 30, is 6, our answer.
Why does that always work? Every present value is counted once in the expected total and once in the actual sum, so it cancels in the subtraction. The missing value is counted only in the expected total, so it is all that remains. That is the teacher saying the roll numbers should add to 36, the room adds to 30, so the absent student is number 6.
There is one trap, and it catches many careful people. For n = 100,000 the expected total is 5,000,050,000, about five billion, and a Java int holds only up to about 2.1 billion. If we compute n * (n + 1) / 2 with ints, the multiplication overflows, which means it wraps around to a wrong number, here 705,082,704, without any error. The cure is to do the arithmetic in a long, which holds far larger numbers.
A second summary avoids overflow altogether, and it uses XOR. XOR, written ^ in Java, compares two numbers bit by bit, where a bit is one binary digit, a 0 or a 1. Each result bit is 1 when the two input bits differ and 0 when they are the same. For example 6 is 0110 in binary and 3 is 0011, so 6 ^ 3 is 0101, which is 5.
Each row is a number written in four bits. Compared bits are the ones where the two inputs differ, which is where XOR writes a 1.
- first
- 6 = 0110
- second
- 3 = 0011
1Row 0 is 6, written 0110, and row 1 is 3, written 0011. They differ in the two right-hand bits.
- 6 ^ 3
- 0101 = 5
26 ^ 3 puts a 1 wherever the bits differ, giving 0101, which is 5. The information about 3 is now mixed into the result.
- 5 ^ 3
- 0110 = 6
- rule
- x ^ a ^ a = x
3XOR the result with 3 again: 0101 ^ 0011 = 0110, which is 6. The two 3s cancelled, and the 6 we started with comes back.
The picture shows the one fact we need. XOR-ing the same number in twice cancels it, because each of its bits flips a result bit and then flips it back. In symbols, x ^ x = 0 and x ^ 0 = x. And the order does not matter, so a ^ b ^ a is the same as a ^ a ^ b, which is b.
A beginner usually asks here why the order should not matter, since the array is all jumbled. Think of each bit position as a light switch that each number may flip. A light ends up on if it was flipped an odd number of times, and the order of the flips changes nothing. So we can XOR every value from 1 to n and every value in the array in any order we like. Each present value is XOR-ed in twice, once from the register and once from the array, and cancels. The missing value is XOR-ed in only once and is what remains.
XOR never carries from one bit to the next the way addition does, so the running result never grows larger than the numbers involved and cannot overflow. That is why many interviewers enjoy the XOR version, though the sum in a long is just as correct.
5Watching the pairs cancel on the example
The picture plays the XOR method exactly as the code runs it. First a loop XORs the register, 1 to 8, into x. Then a second loop XORs each array value in. Watch the panel. Each time an array value goes in, it cancels its partner in the register, and we mark both as done. At the end the only register value without a partner is left in x.
Top row: the register 1 to 8. Bottom row: the array. A done value has cancelled with its partner. The panel shows x in decimal and in binary.
- x
- 0
- binary
- 0000
1We start with x = 0. XOR-ing 0 with anything gives that thing back, so 0 is a safe starting value.
- x
- 8
- binary
- 1000
- contains
- 1 ^ 2 ^ ... ^ 8
2The first loop XORs 1 to 8 into x. The result happens to be 8, which is 1000 in binary. Every register value is now inside x.
- x
- 11
- binary
- 1011
- just added
- 3
3The second loop begins with 3. x ^ 3 = 11, and the 3 now in x twice, once from the register and once from the array, cancels.
- x
- 12
- binary
- 1100
- just added
- 7
4Next is 7. x ^ 7 = 12, and the two 7s cancel.
- x
- 13
- binary
- 1101
- just added
- 1
5Next is 1. x ^ 1 = 13, and the two 1s cancel.
- x
- 15
- binary
- 1111
- just added
- 2
6Next is 2. x ^ 2 = 15, and the two 2s cancel. The numbers in x look meaningless, but the pairs are quietly disappearing.
- x
- 7
- binary
- 0111
- just added
- 8
7Next is 8. x ^ 8 = 7, and the two 8s cancel.
- x
- 3
- binary
- 0011
- just added
- 4
8Next is 4. x ^ 4 = 3, and the two 4s cancel.
- x
- 6
- binary
- 0110
- just added
- 5
9The last value is 5. x ^ 5 = 6, and the two 5s cancel. Every array value has found its partner.
- x
- 6
- binary
- 0110
- answer
- 6
10Only 6 was XOR-ed in once, from the register, with no partner in the array. So x = 6, and we return it.
Let us read a few frames back. In the second frame x is 8, which looks like a strange thing to hold, but it is simply the combined XOR of all eight register values. In the middle frames the numbers in x jump around, 11, 12, 13, 15, 7, 3, and a beginner may worry that something is wrong. Nothing is. We never need to understand those middle values, only that each array value cancels one register value.
In the last frames the cancelling is complete. Seven pairs have vanished, and the one register value with no partner, 6, is what x holds. The sum method agrees: 36 - 30 = 6.
6The complete Java program
Here is the complete program, with both methods side by side. main runs our example with both, then an empty array, a case where n itself is missing, and a case where 1 is missing.
Let us read missingByXor in the order it runs. First we work out n as nums.length + 1, because the array is one short of the register. x starts at 0, which changes nothing when XOR-ed. The first loop XORs every value from 1 to n into x, the whole register. The second loop XORs every array value into x, and each one cancels its partner. What is left is returned.
Now missingBySum. Notice that n is declared as a long, not an int. That one word is what makes n * (n + 1) compute in 64 bits, so the multiplication cannot overflow for any array that fits in memory. actual is a long for the same reason, since the sum of the array can also pass the int limit. At the end the difference is small, a value between 1 and n, so casting it back to int is safe.
The tempting mistake is to write int n and long expected = n * (n + 1) / 2, thinking the long on the left protects us. It does not. Java computes n * (n + 1) in int arithmetic first, because both sides are ints, and only then widens the already wrong result to a long. The type of the variables in the expression decides, not the type of the variable receiving the result.
The program prints 6 and 6 for the example. For the empty array n is 1, the first loop XORs 1 into x, the second loop does nothing, and we return 1. For [1, 2, 3] n is 4, and the XOR of 1 to 4 against 1, 2 and 3 leaves 4. For [2] the answer is 1.
7How much it costs, and the cases at the edges
Let us count on the example first. The XOR version ran its first loop 8 times and its second 7 times, 15 XORs in all, against 28 checks for the brute force. In general it does n + (n - 1) steps of constant work, so the time is O(n). The sum version does the same, one pass over the array plus a formula. Both keep a single running number, so the extra space is O(1).
| Approach | Time | Extra space | Watch out for |
|---|---|---|---|
| Search for each candidate | O(n^2) | O(1) | slow for large n |
| Sort, then find the gap | O(n log n) | O(1) to O(n) | changes the array |
| Boolean seen array | O(n) | O(n) | memory |
| Sum formula in a long | O(n) | O(1) | overflow if done in int |
| XOR of expected and actual | O(n) | O(1) | nothing |
Now the edge cases. An empty array means n is 1, and both methods return 1. When the largest value is missing, as in [1, 2, 3], the register 1 to 4 leaves 4. When the smallest is missing, as in [2], we get 1. Neither case needs special code, because the register always includes both ends.
One honest warning belongs here. Both methods trust the promise in the question. If a value repeats, or falls outside 1 to n, they return a wrong number without noticing. In production code, where input cannot always be trusted, the boolean seen array is safer, because it can detect a repeat or an out-of-range value as it fills.
8Follow-up questions
What if two numbers are missing?
XOR everything as before, and the result is a ^ b for the two missing values a and b. Since a and b are different, at least one bit of a ^ b is 1, and we can pick the lowest such bit with x & -x. That bit splits all the numbers into two groups, those with the bit set and those without, and a and b fall into different groups. XOR-ing each group separately, register values and array values, leaves a in one group and b in the other. It is still O(n) time and O(1) space.
What if the array is sorted?
Then binary search finds the answer in O(log n). Before the gap, every value equals its index plus one, so nums[0] is 1 and nums[1] is 2. After the gap, every value equals its index plus two. So we search for the first index i where nums[i] is not i + 1, and the missing value is i + 1. If there is no such index, the missing value is n.
How would you find a repeated number instead?
If the array holds n + 1 values from 1 to n with one value appearing twice, the same XOR idea works. XOR 1 to n with every array value, and the repeated value, which now appears three times in total, survives while every other value cancels. If the duplicate may appear many times, a different trick is needed, such as treating the array as a chain where index i leads to nums[i] and finding where the chain loops.
9Conclusion
We found the missing number by comparing the register with the room in a single number. The sum method subtracts the actual total from n(n + 1) / 2, computed in a long to avoid overflow. The XOR method XORs 1 to n with every array value, so each present value cancels and only the missing one is left. Both take O(n) time and O(1) space. The clue to remember is from 1 to n: when you know exactly what should be present, summarise expected and actual the same way and let them cancel.
Open with
Let me confirm: the array has n minus 1 distinct values from 1 to n, in any order, exactly one is missing, and I should not modify the array.
Then, if they want more
Checking each candidate against the whole array is O(n squared), and a boolean seen array is O(n) time but O(n) space. Because I know exactly which values should be present, I can summarise them in one number.
The sum of 1 to n is n times n plus 1 over 2, so the missing value is that minus the array's sum, and I compute it in a long because the total passes the int limit once n is about 65,000. A cleaner version uses XOR.
I XOR every value from 1 to n and every value in the array into one variable. Since x XOR x is 0, x XOR 0 is x, and order does not matter, each present value cancels and only the missing one remains. XOR cannot overflow. That is O(n) time and O(1) space.
An empty array gives 1, and both ends of the range are handled because the register includes them.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 15 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An array holds n-1 distinct integers from 1 to n; find the one that is missing.": https://scrivio-interview-library.netlify.app/data-structures/solutions/an-array-holds-n-1-distinct-integers-from-1-to-n-find-the-one-th-7bdfc1/