# O(N) time, O(1) space Java solution

• public class Solution {

``````public int missingNumber(int[] nums) {
int len = nums.length;

int sum = 0;
for(int i = 0; i < len; ++i)
sum += nums[i];

int ideal_sum = 0;
ideal_sum = (0+len)*(len+1)/2;

return ideal_sum - sum;
}
``````

}

• very good and explicit answer!

nums = {0,1,2,3}
what should be returned??4 or 0??

• Prefer this to be simpler,

``````public int missingNumber(int[] nums) {
int result = nums.length;
for (int i = 0; i < nums.length; i++) {
result += i - nums[i];
}
return result;
}``````

• What about overflow? For instance, [0, 1, 2, Integer.MAX_VALUE]. For that situation, this algorithm may need a little modification to apply.

• n numbers are selected from n+1 numbers (0, 1, 2, ....n).

In your example, n=3, so the largest number is 3.

It should return 0, not 4.

• This post is deleted!

• I think if overflow is to be considered , then size of the array also has to be Integer.MAX_VALUE ..

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.