Skip to content

Commit 020825f

Browse files
author
harshbhardwaj
committed
Array: Missing Number in n
1 parent 3f33728 commit 020825f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.practise;
2+
/*
3+
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
4+
5+
Example 1:
6+
7+
Input: [3,0,1]
8+
Output: 2
9+
Example 2:
10+
11+
Input: [9,6,4,2,3,5,7,0,1]
12+
Output: 8
13+
Note:
14+
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
15+
*/
16+
17+
public class MissingNumbers {
18+
public int missingNumber(int[] nums) {
19+
20+
int actualSum = 0;
21+
int largest=0;
22+
int expectedSum =0;
23+
24+
25+
for (int i=0;i< nums.length;i++){
26+
if(nums[i] > largest){
27+
largest = nums[i];
28+
}
29+
}
30+
31+
if(nums.length > largest) {
32+
expectedSum = nums.length*(nums.length +1)/2;
33+
}else{
34+
expectedSum = largest*(largest + 1)/2;
35+
}
36+
37+
38+
39+
for (int i=0;i< nums.length;i++){
40+
actualSum = actualSum + nums[i];
41+
}
42+
43+
return expectedSum - actualSum;
44+
}
45+
}

0 commit comments

Comments
 (0)