Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find removed term from arithmetic sequence in Python
Suppose we have an array called nums holding n-1 arithmetic sequence terms. One element except the first or last element was removed from the original sequence. We have to find the removed number.
So, if the input is like nums = [5, 7, 11, 13], then the output will be 9 because the items follow an arithmetic sequence with common difference 2, and the missing term at index 2 should be 9.
Algorithm
To solve this, we will follow these steps ?
If size of nums is 2, return the average of the two elements
If first two elements are equal, return that value
Calculate the common difference using binary search
Use binary search to locate the missing element position
Example
Let us see the following implementation to get better understanding ?
def solve(nums):
if len(nums) == 2:
return sum(nums) // 2
if nums[0] == nums[1]:
return nums[0]
lower = nums[0]
upper = nums[-1]
interval = (upper - lower) // len(nums)
pointer = len(nums) // 2
left = 0
right = len(nums) - 1
while left != right:
if nums[pointer] != nums[0] + interval * pointer:
if nums[pointer - 1] == nums[0] + interval * (pointer - 1):
return nums[0] + interval * pointer
else:
right = pointer
pointer = (left + right) // 2
else:
if right - left == 1:
pointer = right
else:
left = pointer
pointer = (left + right) // 2
# Test the function
nums = [5, 7, 11, 13]
print("Missing term:", solve(nums))
Missing term: 9
How It Works
The algorithm uses binary search to efficiently find the missing element:
First, it calculates the common difference of the arithmetic sequence
Then it uses binary search to find where the sequence breaks
When a mismatch is found, it determines if the missing element is just before the current position
Alternative Approach
Here's a simpler approach using the sum formula for arithmetic sequences ?
def find_missing_simple(nums):
n = len(nums) + 1 # Original sequence length
# Calculate common difference
# The difference could be (last - first) / (n - 1)
common_diff = (nums[-1] - nums[0]) // (len(nums))
# Expected sum of complete arithmetic sequence
first_term = nums[0]
expected_sum = n * (2 * first_term + (n - 1) * common_diff) // 2
# Actual sum of given array
actual_sum = sum(nums)
return expected_sum - actual_sum
# Test the function
nums = [5, 7, 11, 13]
print("Missing term:", find_missing_simple(nums))
# Test with another example
nums2 = [2, 6, 10, 14, 18] # Missing 12
print("Missing term:", find_missing_simple(nums2))
Missing term: 9 Missing term: 12
Conclusion
Both approaches effectively find the missing term from an arithmetic sequence. The binary search method has O(log n) complexity, while the sum-based approach is simpler with O(n) complexity for calculating the sum.
---