Java Online Compiler
Example: FindMissingNumberSummation in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindMissingNumberSummation import java.util.Arrays; // Not strictly needed for this approach, but often imported public class Main { public static void main(String[] args) { int[] arr1 = {3, 1, 5, 2}; // Missing 4 System.out.println("Array: " + Arrays.toString(arr1) + ", Missing number: " + findMissingNumberSummation(arr1)); int[] arr2 = {1, 2, 3, 5, 6}; // Missing 4 System.out.println("Array: " + Arrays.toString(arr2) + ", Missing number: " + findMissingNumberSummation(arr2)); int[] arr3 = {2, 3, 4, 5}; // Missing 1 System.out.println("Array: " + Arrays.toString(arr3) + ", Missing number: " + findMissingNumberSummation(arr3)); } /** * Finds the missing number in an array using the summation method. * Assumes numbers from 1 to n+1, with one number missing. * * @param arr The input array of distinct integers. * @return The missing integer. */ public static int findMissingNumberSummation(int[] arr) { // Step 1: Determine 'n', which is the count of present numbers. // The complete sequence would have n + 1 numbers (from 1 to n+1). int n = arr.length; // Step 2: Calculate the expected sum of numbers from 1 to (n+1). // The formula for the sum of an arithmetic series 1 to K is K * (K + 1) / 2. // Here, K = n + 1. long expectedSum = (long) (n + 1) * (n + 2) / 2; // Step 3: Calculate the actual sum of elements present in the array. long actualSum = 0; for (int num : arr) { actualSum += num; } // Step 4: The difference is the missing number. return (int) (expectedSum - actualSum); } }
Output
Clear
ADVERTISEMENTS