You can find the missing number in an array containing numbers from 1 to N (with one number missing) by calculating the sum of the first N natural numbers and then subtracting the sum of the given array. The difference will be the missing number. Here's a Python function to accomplish this:
def find_missing_number(arr, N):
expected_sum = N * (N + 1) // 2
actual_sum = sum(arr)
missing_number = expected_sum - actual_sum
return missing_number
# Example usage:
arr = [1, 2, 4, 6, 3, 7, 8]
N = len(arr) + 1 # N is the size of the original array + 1
result = find_missing_number(arr, N)
print("Missing number:", result)
In this example, the find_missing_number
function takes the array arr
and the size N
as parameters. It calculates the expected sum of the first N natural numbers using the formula N * (N + 1) // 2
and then subtracts the sum of the given array to find the missing number.