703333. Missing element of AP

Medium

Missing Element of AP

Summary

The problem is to find a missing element in an arithmetic progression (AP) given its first term and common difference. The AP contains all positive integers from 1 to N, but one element is missing. We need to identify the missing element using binary search.

Detailed Explanation

To solve this problem, we can use a modified binary search algorithm. First, we calculate the total sum of the AP up to N using the formula n*(2*a+(n-1)*d), where a is the first term and d is the common difference. Then, we compare this sum with the actual sum of the AP excluding the missing element. If the sums are equal, the missing element is at the middle index. If not, we continue the binary search process until we find the missing element.

Here's a step-by-step breakdown:

  1. Calculate the total sum of the AP using the formula: n*(2*a+(n-1)*d)
  2. Compare this sum with the actual sum of the AP excluding the missing element.
  3. If the sums are equal, the missing element is at the middle index.
  4. If not, calculate the middle index and find the expected value at that index using the formula: a + (mid - 1) * d
  5. Compare this expected value with the actual value at the middle index. If they match, return the middle index as the missing element.
  6. If they don't match, update the search range and repeat steps 2-5 until we find the missing element.

The time complexity of this algorithm is O(logN), where N is the total number of elements in the AP. The space complexity is O(1) since we only use a constant amount of space to store the variables.

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static void main(String[] args) {
        int n = 5; // Total number of elements
        int a = 2; // First term
        int d = 3; // Common difference
        int missingElement = findMissingElement(n, a, d);
        System.out.println("The missing element is: " + missingElement);
    }

    public static int findMissingElement(int n, int a, int d) {
        long expectedSum = (n * (2 * a + (n - 1) * d)) / 2;
        for (int i = 0; i < n; i++) {
            if ((a + (i * d)) != expectedSum) {
                return a + (i * d);
            }
        }
        return -1; // Missing element not found
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.