⬅ Previous Topic
Union of Two ArraysNext Topic ⮕
Max Consecutive Ones in Array⬅ Previous Topic
Union of Two ArraysNext Topic ⮕
Max Consecutive Ones in ArrayTopic Contents
You are given an array of N-1 distinct integers in the range 1
to N
. The task is to find the one number that is missing from the array.
The array has no duplicates, and only one number is missing. The numbers can be in any order.
Your goal is to identify the missing number efficiently.
N*(N+1)/2
.def find_missing_number(arr, N):
total = N * (N + 1) // 2
actual_sum = sum(arr)
return total - actual_sum
# Sample Input
arr = [1, 2, 4, 5, 6]
N = 6
print("Missing Number:", find_missing_number(arr, N))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | We need to iterate through the array once to calculate the actual sum, which takes linear time. |
Average Case | O(n) | Regardless of the input distribution, we always sum all elements, resulting in linear time complexity. |
Average Case | O(n) | In the worst case, the missing number is at the end, but we still iterate the full array, so the time remains linear. |
O(1)
Explanation: Only a constant number of variables are used to store sums and the final result. No extra space proportional to input size is required.
⬅ Previous Topic
Union of Two ArraysNext Topic ⮕
Max Consecutive Ones in ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.