Taro Logo

Missing Number In Arithmetic Progression

Easy
Asked by:
Audible
0 views
Topics:
ArraysBinary Search

In some array arr, the values were in arithmetic progression: the values arr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1.

A value from arr was removed that was not the first or last value in the array.

Given arr, return the removed value.

Example 1:

Input: arr = [5,7,11,13]
Output: 9
Explanation: The previous array was [5,7,9,11,13].

Example 2:

Input: arr = [15,13,12]
Output: 14
Explanation: The previous array was [15,14,13,12].

Constraints:

  • 3 <= arr.length <= 1000
  • 0 <= arr[i] <= 105
  • The given array is guaranteed to be a valid array.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array contain negative numbers, zeros, and floating-point values, or are we strictly dealing with integers?
  2. What is the minimum possible length of the input array, and can the sequence be either strictly increasing or strictly decreasing?
  3. Is the input array guaranteed to be unsorted, or could it be provided in any order?
  4. Are there any duplicate values allowed in the input array?
  5. What should be returned if the input array has fewer than three elements, making it impossible to determine a missing number?

Brute Force Solution

Approach

The problem asks us to find a single missing number in an arithmetic progression. Because the first and last elements are guaranteed not to be missing, we can deduce the constant difference directly from them. We then iterate through the array until the difference between consecutive elements does not match the expected step.

Here's how the algorithm would work step-by-step:

  1. Determine the count of elements that the original array contained before one was removed.
  2. Compute the constant difference of the arithmetic progression by dividing the span between the last and first elements by the number of steps.
  3. Iterate through adjacent pairs in the given array.
  4. Check if the next element matches the current element plus the common difference.
  5. Return the expected value when a mismatch is found.

Code Implementation

def missing_number(arr):
    # Calculate the total number of elements in the complete progression.
    total_elements = len(arr) + 1
    # Determine the common difference using the first and last elements.
    common_difference = (arr[-1] - arr[0]) // (total_elements - 1)
    # Traverse the array to locate the missing value.
    for index in range(len(arr) - 1):
        expected_value = arr[index] + common_difference
        if arr[index + 1] != expected_value:
            return expected_value
    return arr[0]

Big(O) Analysis

Time Complexity
O(n) – We iterate through the array of length n at most once to check the difference between adjacent elements, leading to a linear time complexity.
Space Complexity
O(1) – Only a few scalar variables are used to store differences and loop counters, requiring constant extra memory.

Optimal Solution

Approach

The arithmetic progression is missing exactly one element that is neither the first nor the last term. By determining the total difference between the ends and dividing by the expected number of steps, we can deduce the true common difference. Using binary search, we locate the earliest index where the actual value deviates from the expected value to find the missing number.

Here's how the algorithm would work step-by-step:

  1. Compute the true common difference by dividing the difference between the last and first element by the array length.
  2. Initialize two pointers representing the search boundary across the array indices.
  3. In each step of the binary search, calculate the midpoint and its expected value based on the common difference.
  4. If the value at the midpoint matches the expected value, the missing number must be in the right half.
  5. Otherwise, the missing number is in the left half, so shrink the search space accordingly.
  6. After terminating the search, compute and return the missing value using the detected position.

Code Implementation

def find_missing_number(arr: list[int]) -> int:
    # Calculate the expected common difference of the full progression
    total_diff = (arr[-1] - arr[0]) // len(arr)
    left_index = 0
    right_index = len(arr) - 1
    # Use binary search to locate where the discrepancy begins
    while left_index < right_index:
        mid_index = (left_index + right_index) // 2
        expected_value = arr[0] + mid_index * total_diff
        # Check if the arithmetic sequence holds up to mid_index
        if arr[mid_index] == expected_value:
            left_index = mid_index + 1
        else:
            right_index = mid_index
    # The missing number is at the identified gap position
    return arr[0] + left_index * total_diff

Big(O) Analysis

Time Complexity
O(log n) – We perform a binary search over an array of size n, cutting the search interval in half at each step, which requires logarithmic time.
Space Complexity
O(1) – Only a few scalar variables are used to maintain the search pointers and differences, requiring constant extra memory.

Edge Cases

Input array with fewer than three elements
How to Handle:
Since at least three elements are required to determine the progression and the missing spot, we must validate input size and throw an error or return default.
Array with a constant difference of zero
How to Handle:
The arithmetic difference can be zero if all elements are identical, which we handle by calculating the difference safely without division by zero.
Missing number is at the very beginning of the sequence
How to Handle:
Comparing differences across multiple index intervals ensures we correctly identify the step size even when the first term is absent.
Missing number is at the very end of the sequence
How to Handle:
Checking the difference at both the start and end of the sorted array allows us to detect missing terminal values accurately.
Input containing large negative and positive numbers
How to Handle:
Using standard arithmetic subtraction handles negative and positive ranges seamlessly without sign distortion.
Unsorted input array
How to Handle:
Sorting the array first in logarithmic time ensures that consecutive elements are adjacent for straightforward difference checking.
Extremely large inputs approaching memory or time limits
How to Handle:
A binary search approach running in logarithmic time or an optimal linear scan avoids timeouts and memory overflow.
Integer overflow during difference calculations
How to Handle:
Casting integers to 64-bit equivalents prevents overflow when computing differences between extremely large boundary values.