703156. Find the left over element

Easy

Find the Left Over Element

Summary

This problem requires you to find the leftover element in an array. The array is sorted, and one element is missing. Your task is to write a program that finds this missing element.

Detailed Explanation

The given array is already sorted. We can solve this problem by iterating through the array and comparing each element with its previous and next elements. If we find any pair of adjacent elements which have different values, then the middle element in that range will be the missing one.

Here's a step-by-step breakdown:

  1. Initialize two pointers, start and end, to the beginning and end of the array.
  2. Compare the elements at the start and end indices.
  3. If the difference between these elements is greater than 1, then the missing element must be in this range.
  4. Move the pointer that points to the smaller element towards the other pointer until the difference becomes 1 or less.
  5. The middle element of this range will be the missing one.

Time complexity: O(n) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static int findMissingElement(int[] arr) {
        if (arr.length < 2) return -1;

        int start = 0;
        int end = arr.length - 1;

        while (start <= end) {
            int diff = Math.abs(arr[start] - arr[end]);

            if (diff > 1) {
                if ((arr[start + 1] - arr[start]) == 1)
                    return arr[start] + 1;
                else if ((arr[end] - arr[end - 1]) == 1)
                    return arr[end] - 1;

                start++;
                end--;
            } else {
                if (diff == 0) return -1; // duplicate elements
                if (start == end) return arr[start]; // single element array

                start++;
                end--;
            }
        }

        return -1;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.