How do you find the missing number in a given integer array of 1 to 100?

 There are several ways to find the missing number in a given integer array of numbers from 1 to 100. Here are a few of them:



  1. Using a Hash Set: This is a simple solution that uses a hash set to store the numbers in the array. Then, iterate over the numbers from 1 to 100 and check if each number is present in the hash set. If a number is not found in the hash set, it is the missing number.
  2. Using Sum Formulas: Calculate the expected sum of the numbers from 1 to 100, and then subtract the actual sum of the numbers in the array. The result will be the missing number.
  3. Using XOR: This is a more efficient solution that uses XOR. XOR all the numbers from 1 to 100, and then XOR all the numbers in the array. The result will be the missing number.
  4. Using Binary Search: This solution is similar to the binary search algorithm, but instead of searching for a specific number, you are searching for the missing number. Start by checking the middle number in the range of numbers from 1 to 100. If the middle number is not in the array, the missing number must be in the lower half of the range. If the middle number is in the array, the missing number must be in the upper half of the range. Repeat this process until the missing number is found.


These are just a few examples of how you might find the missing number in a given integer array. The choice of solution will depend on the specific requirements of your problem and the trade-offs you are willing to make between time and space complexity.

Below is the solution link with different way : 

Using HashSet:




package main

import (
	"fmt"
)

func findMissingNumber(nums []int) int {
	// Create a map to store the numbers in the array
	numbers := make(map[int]bool)

	// Add each number in the array to the map
	for _, num := range nums {
		numbers[num] = true
	}

	// Iterate over the numbers from 1 to 100
	for i := 1; i <= 100; i++ {
		// Check if each number is present in the map
		if !numbers[i] {
			// If a number is not found in the map, it is the missing number
			return i
		}
	}

	// Return 0 if all numbers are present in the array
	return 0
}

func main() {
	nums := []int{1, 2, 3, 4, 5, 7, 8, 9, 10}
	missing := findMissingNumber(nums)
	fmt.Println("The missing number is:", missing)
}


In this example, the function findMissingNumber takes an array of integers as input, and returns the missing number. The function uses a map to store the numbers in the array, and then iterates over the numbers from 1 to 10 to check if each number is present in the map. If a number is not found in the map, it is the missing number.

Post a Comment

0 Comments