Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Programming Challenge: Find the Missing Number in a Sequence

1. How to find the missing number in a sequence?

A common programming task involves finding a missing element in a sequence of integers. This is a practical problem often encountered in technical interviews and production code where data integrity needs to be verified.

Given an array A consisting of N different integers taken from the range 1 to N+1, find the missing number.

Example:

  • Input: A = {2, 3, 1, 5}
  • Output: 4
  • Explanation: All numbers from 1 to 5 should be present. The number 4 is missing.

Solution Strategy:

  • Use the mathematical formula for the sum of the first N+1 natural numbers: sum = (N + 1) * (N + 2) / 2
  • Subtract the sum of the array elements from the expected sum to find the missing number.

Java Implementation:


public class MissingNumberFinder {
    public int findMissing(int[] A) {
        int N = A.length;
        long expectedSum = (long)(N + 1) * (N + 2) / 2;
        long actualSum = 0;
        for (int value : A) {
            actualSum += value;
        }
        return (int)(expectedSum - actualSum);
    }

    public static void main(String[] args) {
        MissingNumberFinder finder = new MissingNumberFinder();
        int[] input = {2, 3, 1, 5};
        System.out.println("Missing number: " + finder.findMissing(input));
    }
}
                

Output: Missing number: 4

Time Complexity: O(N)

Space Complexity: O(1)

Edge Case Considerations:

  • Empty array → should return 1
  • Array with one number (e.g., [2]) → should return 1
  • Sequential array with last element missing (e.g., [1, 2, 3, 4]) → should return 5