Your task is to find the missing number.
# prompt: You are given an array of size N-1 containing distinct numbers from 1 to N. This means one number from the range 1 to N is missing. Your task is to find the missing number.
def find_missing_number(arr):
n = len(arr) + 1 # Calculate the expected size of the array
expected_sum = n * (n + 1) // 2 # Calculate the sum of numbers from 1 to N
actual_sum = sum(arr) # Calculate the sum of the given array elements
missing_number = expected_sum - actual_sum # Find the missing number
return missing_number
# Example usage:
arr = [1, 2, 4, 6, 3, 7, 8]
missing_num = find_missing_number(arr)
print(f"The missing number is: {missing_num}")
Comments
Post a Comment