Quick revision
The short answer
Finding the one missing number in 1 to n is a math and bits problem: we know the complete set, so one summary number of each side is enough. Subtract the array's sum from n(n + 1) / 2, computed in long, or XOR the numbers 1 to n with every element so that present numbers cancel and the missing one remains. Both take O(n) time and O(1) space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Search for every number | O(n^2) | O(1) |
| Sort, then find the gap | O(n log n) | O(1), reorders the input |
| Boolean seen array | O(n) | O(n) |
| Sum formula in long, or XOR | O(n) | O(1) |
What to remember
We found the missing number in 1 to n without remembering which numbers we had seen. Because the complete set is known, one summary of each side is enough: n(n + 1) / 2 minus the array's sum, done in long to avoid overflow, or the XOR of 1 to n and every element, in which present numbers cancel in pairs. Both take O(n) time and O(1) space. The clue to remember: when you know exactly what a collection should contain and one item is missing, summarise both sides with one number and compare.
1What the question asks, told as a pile of homework
Imagine a teacher whose class has roll numbers 1 to 6. Each student writes their roll number on the homework, and at the end of the day five sheets come back, in no particular order: 4, 1, 6, 2, 5. One student forgot. The teacher could hunt for each roll number in turn, but a quicker teacher would think: the six roll numbers add up to 21, these five add up to 18, so the sheet from roll number 3 is missing. Keep that teacher in mind, because she has already solved our problem.
In the question, the sheets are an int array. It holds the numbers from 1 to n, each at most once, in any order, with exactly one of them missing. Because exactly one is missing, the array has n - 1 elements, so we never need n handed to us: n is a.length + 1. We must return the missing number.
Our example is {4, 1, 6, 2, 5}. Its length is 5, so n is 6, and the answer is 3. A second example is worth keeping too: {1, 2, 3} has length 3, so n is 4, and the missing number is 4 itself, the largest. That case is easy to forget, because nothing in the array hints at a 4.
This problem is smaller than it looks. The answer is a single number, and we will see that we never need to remember which numbers we have already seen. One pass over the array, with one running number, is enough.
The array holds five of the six numbers 1 to 6, in no particular order.
- length
- 5
- n
- 6
- missing
- 3
1The array has five elements, so n is 6. The numbers 1, 2, 4, 5 and 6 are here, in any order, and 3 is the one that never appears.
What to assume
- Is the range 1 to n or 0 to n?
- We assume 1 to n.
- Can a number appear twice?
- No.
- Is the array sorted?
- No.
- How large can n be?
- Up to millions. And the empty array means n is 1, so the answer is 1.
Let us do it by hand first, the slow and sure way. Write 1 to 6 on paper and tick each number as you read the array: 4, tick; 1, tick; 6, tick; 2, tick; 5, tick. The only number without a tick is 3. That works on paper, but it needs a whole row of ticks, one for every number, and we will ask later whether we can do with less.
A careful candidate asks a few questions first. Is the range 1 to n or 0 to n? We assume 1 to n; the other version only shifts the range, as the FAQs show. Can a number appear twice? No. Is the array sorted? No, which matters, because a sorted array allows a faster search. How large can n be? Up to millions, which will matter for overflow. And the empty array means n is 1, so the answer is 1.
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
A beginner reading this question usually reaches for a search: look for 1, then 2, then 3, until one is not found. Others sort the array and look for the gap, or put every number into a HashSet and then ask the set about 1, 2, 3 in turn. All of these work. What they have in common is that they remember or search for individual numbers, and that is more than the question needs.
So let us read the clues one at a time. The first is the phrase the numbers 1 to n. It means we know in advance exactly what a complete array would contain. That is rare. In most problems the data is unknown; here we know the full set before we read a single element.
The second clue is the phrase one missing. The difference between the complete set and the array is a single number. When the difference is one number, we do not need to compare the two collections element by element. We can boil each side down to one summary number, such as its total, and compare the two summaries, exactly as the teacher did with 21 and 18.
Together the clues point to the math and bits pattern. The name means using a fact from arithmetic, such as a formula for a sum, or an operation on the bits of numbers, such as XOR, to summarise a whole collection in one number instead of storing it. The rule to carry to new problems: when you know what a collection should contain and need the small difference, summarise both sides with one number, a sum or an XOR, and compare. The same rule finds the single number that appears once when every other number appears twice.
Some patterns look similar but fit less well. Hashing answers the question but spends O(n) memory on information we never use. Sorting also works but costs O(n log n) time and changes the input. Binary search is excellent when the array is sorted, a case the FAQs cover, but ours is not.
3The brute force, looking for every number in turn
The brute force is the most direct idea. For each candidate k from 1 to n, we scan the array for it and return the first candidate that is not found. It is obviously correct, which makes it a good place to start.
Let us do it by hand on {4, 1, 6, 2, 5}. For k = 1 we read 4 and then 1, found after two looks. For k = 2 we read 4, 1, 6 and 2, four looks. For k = 3 we read all five elements and never meet a 3, so we return 3. That was 2 + 4 + 5 = 11 looks for an array of five.
Now generalise. For each of up to n candidates we may scan up to n - 1 elements, so the time is O(n^2), read as order n squared. The extra memory, called space, is O(1), because we keep only k and found. For a million numbers that could be around half a trillion looks.
Two middle steps improve on it. A boolean array seen of size n + 1, marked in one pass and then scanned for the unmarked number, is our paper of ticks: O(n) time but O(n) extra space. Sorting first and looking for the first index i where a[i] is not i + 1 costs O(n log n) and reorders the caller's array.
So where is the waste? Every scan rereads the same five numbers, and even the seen array stores a tick for every number. Yet we only want one number out of all this. Here is the question that leads forward: can we learn what is missing without remembering which numbers are present?
4Getting to the one-pass answer, from the sum to XOR
The teacher's trick answers yes. Add up what should be there, add up what is there, and subtract. Adding 1 to n by hand is slow, but there is a neat shortcut. Pair the numbers from the outside in: 1 with 6, 2 with 5, 3 with 4. Each pair adds to 7, which is n + 1, and there are 3 pairs, which is n / 2. So the total is n(n + 1) / 2, here 6 times 7 over 2, which is 21. The formula works for odd n too, because n(n + 1) is always even.
expected is what the complete set adds up to; actual is the running total of the array.
- expected
- 21
- actual
- 0
1For n = 6 the complete set should add up to 6 times 7 over 2, which is 21. We have added nothing from the array yet.
- expected
- 21
- actual
- 5
2We add the first two elements, 4 and 1, so the running total of what we actually have is 5.
- expected
- 21
- actual
- 18
3After 6, 2 and 5 the whole array is added, and what we actually have comes to 18.
- expected
- 21
- actual
- 18
- missing
- 21 - 18 = 3
4What should be there minus what is there is 21 - 18 = 3. The difference is exactly the missing number.
Now comes the question a beginner should ask. Can anything go wrong with adding? Yes, the size of the numbers. Java's int holds values up to 2,147,483,647, a little over two billion. With n = 100,000, n(n + 1) is about ten billion, far beyond that, and int arithmetic does not complain; it silently wraps around. Computed in int, 100,000 times 100,001 over 2 gives 705,082,704 instead of 5,000,050,000. The fix is to do the arithmetic in long, which holds numbers up to about nine quintillion. The tempting mistake is to write long expected = n * (n + 1) / 2 with n still an int, because the multiplication then happens in int before the result is widened, so we declare n itself as long.
There is a second summary that cannot overflow at all, and it uses the bits of numbers. Every int is stored as a row of bits, each 0 or 1; for example, 5 is 101, read from the left as one 4, no 2 and one 1. XOR, written ^ in Java, compares two numbers bit by bit and gives 1 where the bits differ and 0 where they are the same. Think of a row of light switches: x ^ v flips every switch in x that is on in v.
Three facts about XOR do all the work, and the switches explain each one. Flipping the same switches twice puts them back, so x ^ x is 0. Flipping nothing changes nothing, so x ^ 0 is x. And the order of the flips does not matter, so we can XOR numbers in any order and get the same result.
Now we arrange a situation where every number but one appears twice. We XOR all numbers from 1 to n, the complete set, and then all elements of the array, the set with one hole. Every present number has now been flipped in twice and cancels to 0. The missing number was flipped in only once, from the range, so it is what remains. No sums are formed, so nothing can overflow, whatever n is.
5Watching XOR find the missing 3
The picture runs missingXor on our example, one XOR per frame, with values taken from a run of the Java code. The first six cells are the range 1 to 6 and the last five are the array, so you can see both loops in one row. The panel shows x in ordinary numbers and in bits.
Do not try to predict x; it jumps around and that is fine. Watch instead what happens to each number: it goes in once from the range and once from the array, and by the end every pair has cancelled.
First the range 1 to 6, then the array. Each present number is folded in twice and cancels; the missing one is folded in once.
- x
- 0 (000)
- n
- 6
- phase
- not started
1The first six cells are the complete range 1 to 6 and the last five are our array. x starts at 0, and we will XOR every cell into it.
- x
- 1 (001)
- step
- x ^= 1
- phase
- range 1 to 6
2x ^= 1. Starting from 0, XOR with 1 simply gives 1, because XOR with 0 changes nothing. In bits, x is 001.
- x
- 3 (011)
- step
- x ^= 2
- phase
- range 1 to 6
3x ^= 2. 001 and 010 differ in two places, so those two bits are on and x becomes 011, which is 3.
- x
- 0 (000)
- step
- x ^= 3
- phase
- range 1 to 6
4x ^= 3. 011 and 011 are the same, so every bit switches off and x is 0. Equal numbers cancel completely.
- x
- 4 (100)
- step
- x ^= 4
- phase
- range 1 to 6
5x ^= 4. Starting again from 0, XOR with 4 gives 4, which is 100 in bits.
- x
- 1 (001)
- step
- x ^= 5
- phase
- range 1 to 6
6x ^= 5. 100 and 101 differ only in the right bit, so x becomes 001, which is 1.
- x
- 7 (111)
- step
- x ^= 6
- phase
- range 1 to 6
7x ^= 6. 001 and 110 differ in all three bits, so x becomes 111, which is 7. The whole range 1 to 6 is now folded into x.
- x
- 3 (011)
- step
- x ^= 4
- phase
- array elements
8Now the array. x ^= 4: 111 and 100 differ in the right two bits, so x becomes 011, which is 3. The 4 from the range is cancelled.
- x
- 2 (010)
- step
- x ^= 1
- phase
- array elements
9x ^= 1: 011 and 001 differ in the middle bit, so x becomes 010, which is 2. The 1 from the range is cancelled.
- x
- 4 (100)
- step
- x ^= 6
- phase
- array elements
10x ^= 6: 010 and 110 differ in the left bit, so x becomes 100, which is 4. The 6 from the range is cancelled.
- x
- 6 (110)
- step
- x ^= 2
- phase
- array elements
11x ^= 2: 100 and 010 differ in two bits, so x becomes 110, which is 6. The 2 from the range is cancelled.
- x
- 3 (011)
- step
- x ^= 5
- phase
- array elements
- missing
- 3
12x ^= 5: 110 and 101 differ in the right two bits, so x becomes 011, which is 3. Every present number cancelled, and 3 is left.
Let us read some frames back. The third XOR is worth a pause: after 1, 2 and 3, x is 0, because 1 ^ 2 is 3, and 3 ^ 3 cancels. It shows the cancelling at work even before the array starts. After the whole range x is 7, the XOR of 1 to 6, which holds every number of the complete set folded together.
Then the array folds the same numbers in a second time, in a different order: 4, 1, 6, 2, 5. Because order does not matter, each one cancels its partner from the range, whatever position it is in. In the last frame every pair is dimmed and only the 3 from the range is left, so x is 3, the answer.
Check the bits of one step yourself. At the seventh XOR, x is 111 and the element is 4, which is 100. The left bit is 1 in both, so it switches off, and the right two stay on, giving 011, which is 3.
6The complete Java program
Here is the full program with both one-pass methods. main tries our example with each method, a missing largest number, a missing 1, the empty array, and a large test of 1 to 100,000 without 77,777, where an int sum would already have overflowed. Each comment shows what that line prints.
Let us read missingXor in the order it runs. First n = a.length + 1, because exactly one number is missing; working n out ourselves means a caller cannot pass the wrong one. Then x starts at 0, because XOR with 0 changes nothing, so 0 is the natural empty starting point, like 0 for a sum.
The first loop folds the complete set 1 to n into x, and the second folds in every element of the array. We do not need the elements in any particular order and we never change the array. After both loops x holds the missing number.
In missingSum, notice that n is declared long, not int. That one word is what makes n * (n + 1) safe. actual is a long for the same reason, and only at the end do we cast the difference back to int, which is safe because the answer is at most n.
So main prints 3 and 3 for our example, 4 for {1, 2, 3}, 1 for {2, 3, 4}, 1 for the empty array, where n is 1, and 77777 77777 for the large test, which shows the two methods agree at a size where int arithmetic would break.
7How much it costs, and the cases at the edges
Let us count on the example first. missingXor did 6 XORs for the range and 5 for the array, 11 in all, and missingSum did 5 additions plus one formula. For n numbers that is about 2n steps for XOR and n for the sum, so both run in O(n) time. We cannot do better on an unsorted array, because any element we skip might be the one that rules a number in or out.
Both keep one or two variables, so the extra space is O(1), and neither changes the input. XOR has the edge in robustness, because it can never overflow; the long sum is safe for any array that fits in memory.
| Approach | Time | Extra space |
|---|---|---|
| Search for every number | O(n^2) | O(1) |
| Sort, then find the gap | O(n log n) | O(1), reorders the input |
| Boolean seen array | O(n) | O(n) |
| Sum formula in long, or XOR | O(n) | O(1) |
The edge cases are handled without special code. If the missing number is n, as in {1, 2, 3}, the range loop includes n and the array never cancels it. If it is 1, as in {2, 3, 4}, the same holds for 1. The empty array gives n = 1, the range loop runs once, and we return 1. The array's order never matters.
One honest warning. If the promise is broken, say a number appears twice or two are missing, both methods quietly return a wrong number. In production code we would validate the input or use the seen array, which can notice a duplicate.
8Follow-up questions
What if two numbers are missing?
XOR of the range and the array then gives x ^ y, the two missing numbers folded together, and since x and y are different, at least one bit of that result is 1. That bit is a place where x and y differ: one of them has a 1 there and the other a 0. So we split every number, from the range and from the array, into two groups by that bit, and XOR each group on its own. Inside each group the present numbers still cancel in pairs, and each group leaves exactly one missing number. It stays O(n) time and O(1) space. Another route uses the sum and the sum of squares to write two equations for x and y.
What if the array is sorted?
Then we can do better than a full pass. In a sorted array, every element before the gap equals its index plus one, and every element after it equals its index plus two. For {1, 2, 4, 5, 6}, a[1] is 2 but a[2] is 4. So we binary search for the first index i where a[i] is not i + 1, halving the range each time, and the missing number is i + 1. That takes O(log n) time. If no such index exists, the missing number is n.
What changes if the numbers run from 0 to n?
Only the range. The array then has n elements, so n is a.length, and the complete set is 0 to n. XOR works unchanged if the first loop runs from 0, which adds nothing, to n. A neat version XORs each index i with a[i] inside one loop and then XORs n at the end, because the indexes 0 to n - 1 together with n are exactly the complete set.
9Conclusion
We found the missing number in 1 to n without remembering which numbers we had seen. Because the complete set is known, one summary of each side is enough: n(n + 1) / 2 minus the array's sum, done in long to avoid overflow, or the XOR of 1 to n and every element, in which present numbers cancel in pairs. Both take O(n) time and O(1) space. The clue to remember: when you know exactly what a collection should contain and one item is missing, summarise both sides with one number and compare.
Open with
Let me confirm: the array holds distinct numbers from 1 to n with exactly one missing, in any order, so n is the length plus one, and the empty array means the answer is 1.
Then, if they want more
The brute force looks for each candidate, which is O(n squared), and a boolean seen array is O(n) time but O(n) space. Since I know the complete set, I only need one summary of each side. The sum of 1 to n is n times n plus one over two, so I subtract the array's sum.
For n around 100,000 that product overflows an int, so I compute it in long. An alternative that cannot overflow at all is XOR.
X XOR x is zero, x XOR zero is x, and order does not matter, so if I XOR every number from 1 to n and then every element, each present number appears twice and cancels, and the missing number is left.
For 4, 1, 6, 2, 5, the XOR of 1 to 6 is 7, and folding in the array gives 3. Both are one pass, O(n) time and O(1) space, and neither changes the input. If the array were sorted, I would binary search for the first index where the value is not index plus one, in O(log n).
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 43 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 the numbers 1 to n with one missing. Find the missing number.": https://scrivio-interview-library.netlify.app/data-structures/solutions/an-array-holds-the-numbers-1-to-n-with-one-missing-find-the-miss-86dcdc/