There was an error while loading. Please reload this page.
1 parent d200d74 commit 14eefbbCopy full SHA for 14eefbb
Java/missing-number.java
@@ -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