Problem Statement
You are given a sorted array of N
integers from 1 to N
with one number missing. Find the missing number.
Examples
Example 1:
Input: ar[] = {1, 3, 4, 5}
Output: 2
Example 2:
Input: ar[] = {1, 2, 3, 4, 5, 7, 8}
Output: 6
Approach 1: Brute Force
Idea
Check every number from 1
to N
to see if it's missing in the array.
Steps
- Iterate from
1
to N
.
- For each number, check if it is present in the array.
- If a number is missing, return it.
Time Complexity
- O(n^2) (due to searching in an array for each number)
Space Complexity
Example Code
Dry Run
ar[] = {1, 3, 4, 5}
- Check 1: present
- Check 2: missing -> return
2
Approach 2: Efficient Approach (Binary Search)
Idea
Use binary search to identify where the missing element is by comparing the values with their expected indices.
Steps
- Initialize
left = 0
and right = N-1
.
- Perform binary search:
- Calculate
mid
.
- If
arr[mid]
matches mid + 1
, the missing element is on the right.
- Otherwise, it's on the left.
- Continue until
left
points to the missing number.
Time Complexity
Space Complexity
Example Code
Dry Run
ar[] = {1, 2, 3, 4, 5, 7, 8}
- Binary search finds that
6
is missing.
Example Test Case
Test Case 1
Input: ar[] = {1, 3, 4, 5}
Output: 2
Test Case 2
Input: ar[] = {1, 2, 3, 4, 5, 7, 8}
Output: 6
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n^2)
- Space Complexity: O(1)
Efficient Approach
- Time Complexity: O(log n)
- Space Complexity: O(1)
Conclusion
The brute force approach is simple but inefficient for larger arrays, with a time complexity of O(n^2). The efficient approach using binary search significantly reduces the time complexity to O(log n), making it well-suited for larger datasets.