Problem Statement:
Given a sorted array representing an arithmetic progression (AP), one element is missing. Write a function to find the missing element using binary search.
Sample Example:
Input: arr = [1, 3, 5, 7, 11]
Output: 9
Explanation: The missing element in the arithmetic progression is 9, which is the expected value between 7 and 11 based on the common difference of 2.
Approaches
Brute Force Approach
-
Idea:
- Calculate the expected difference
d in the progression. Then, iterate through the array and find the position where the difference between consecutive elements is not equal to d. The missing number is found at this position.
-
Steps:
- Calculate the common difference
d.
- Iterate through the array to find the first occurrence where the difference between consecutive elements is not equal to
d.
- Return the missing number based on this mismatch.
-
Time Complexity: O(n)
-
Space Complexity: O(1)
-
Example Code:
- Dry Run:
- Input:
arr = [1, 3, 5, 7, 11]
- Expected difference:
d = 2
- Perform binary search:
- Middle index: 2, element at
arr[2] = 5 is in the correct position.
- Adjust
low = 3.
- Middle index: 3, element at
arr[3] = 7 is in the correct position.
- Adjust
low = 4.
- Missing element:
1 + 4 * 2 = 9.
Example Test Case
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n)
- Space Complexity: O(1)
Binary Search Approach
- Time Complexity: O(log n)
- Space Complexity: O(1)
Conclusion
The binary search approach is more efficient for large arrays, reducing the time complexity from O(n) to O(log n).