Skip to content

Commit d5b6e8d

Browse files
committed
Find Missing Number
1 parent 100f289 commit d5b6e8d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

MathAndStats/FindMissingNumber.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Given an array of positive numbers from 1 to n, such that all numbers from 1 to n are present except one. Find the missing number
3+
4+
1) Brute Force method is to iterate through all the elements and find the missing number. This solution is O(n^2) in time complexity
5+
6+
2) Use the arithematic sum of numbers upto n Sum(numbers upto n) = n(n+1)/2. Do a linear scan of the array and find the sum of the elements and subtract from the arithematic sum to get the missing number. This solution is O(n) as we only traverse through the array once
7+
*/
8+
9+
package main
10+
11+
import ("fmt")
12+
13+
func Sum(array []int) int {
14+
sum := 0
15+
for _,val := range array {
16+
sum += val
17+
}
18+
return sum
19+
}
20+
21+
func ArithematicSum(n int ) int {
22+
return n*(n+1)/2
23+
}
24+
25+
func main() {
26+
array := []int{3,7,1,2,8,4,5}
27+
n := len(array) + 1
28+
fmt.Println("Missing Number is:",(ArithematicSum(n)-Sum(array)))
29+
}

0 commit comments

Comments
 (0)