Go Program to Find Missing Number in Slice
n*(n+1)/2 and subtracting the actual sum of the slice elements; for example, use missing := totalSum - actualSum.Examples
How to Think About It
n*(n+1)/2. Then find the sum of all numbers in the slice. The missing number is the difference between the total sum and the slice sum.Algorithm
Code
package main import "fmt" func findMissingNumber(nums []int) int { n := len(nums) + 1 totalSum := n * (n + 1) / 2 actualSum := 0 for _, num := range nums { actualSum += num } return totalSum - actualSum } func main() { slice := []int{1, 2, 4, 5, 6} missing := findMissingNumber(slice) fmt.Println(missing) }
Dry Run
Let's trace the slice [1, 2, 4, 5, 6] through the code
Calculate n
Length of slice is 5, so n = 5 + 1 = 6
Calculate total sum
totalSum = 6 * (6 + 1) / 2 = 21
Calculate actual sum
Sum of slice elements = 1 + 2 + 4 + 5 + 6 = 18
Find missing number
missing = totalSum - actualSum = 21 - 18 = 3
| Step | Value |
|---|---|
| n | 6 |
| totalSum | 21 |
| actualSum | 18 |
| missing | 3 |
Why This Works
Step 1: Calculate total sum
The formula n*(n+1)/2 gives the sum of all numbers from 1 to n, which is the expected total if no number was missing.
Step 2: Sum slice elements
Adding all numbers in the slice gives the actual sum of present numbers.
Step 3: Subtract to find missing
Subtracting the actual sum from the total sum reveals the missing number because it accounts for the gap.
Alternative Approaches
package main import "fmt" func findMissingBoolean(nums []int) int { n := len(nums) + 1 present := make([]bool, n+1) for _, num := range nums { present[num] = true } for i := 1; i <= n; i++ { if !present[i] { return i } } return -1 } func main() { slice := []int{1, 2, 4, 5, 6} missing := findMissingBoolean(slice) fmt.Println(missing) }
package main import "fmt" func findMissingXOR(nums []int) int { n := len(nums) + 1 xor := 0 for i := 1; i <= n; i++ { xor ^= i } for _, num := range nums { xor ^= num } return xor } func main() { slice := []int{1, 2, 4, 5, 6} missing := findMissingXOR(slice) fmt.Println(missing) }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops once through the slice to sum elements, so time grows linearly with slice size.
Space Complexity
Only a few variables are used, so space is constant regardless of input size.
Which Approach is Fastest?
The sum formula method is fastest and simplest; XOR is also O(n) but less intuitive; boolean map uses extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sum formula | O(n) | O(1) | Simple and fast for numeric ranges |
| Boolean map | O(n) | O(n) | Easy to understand, uses extra memory |
| XOR operation | O(n) | O(1) | Efficient and no extra memory, but less intuitive |
n*(n+1)/2 to quickly find the missing number without extra memory.