Skip to content

Commit 14eefbb

Browse files
Create missing-number.java
1 parent d200d74 commit 14eefbb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Java/missing-number.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Time Complexity - O(n)
3+
* Space Complexity - O(1)
4+
*
5+
* Using sum of first n natural numbers formula.
6+
*/
7+
class Solution {
8+
public int missingNumber(int[] nums) {
9+
int numsLen = nums.length;
10+
11+
// sum of n natural number is
12+
// Sn = n * (n+1)/2
13+
int expectedSum = numsLen*(numsLen+1)/2;
14+
15+
// calculate actual sum
16+
int actualSum = 0;
17+
for (int i=0; i<numsLen; i++){
18+
actualSum += nums[i];
19+
}
20+
21+
// subtract actualSum from expectedSum
22+
return expectedSum-actualSum;
23+
}
24+
}

0 commit comments

Comments
 (0)