Skip to content

Commit 3db7d38

Browse files
committed
Find the missing number in 1 to N
1 parent adb0e66 commit 3db7d38

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.java.array;
2+
/*
3+
* Find the Missing Number in 1 to N
4+
*
5+
* An array contains 1 to N numbers
6+
* but one number in the array is missing
7+
* Write the java program to find the missing no
8+
*
9+
* Steps:
10+
* 1. Calculate the sum of the array
11+
* 2. Calculate the sum of 1 to N
12+
* 3. Subtract array from the expected sum
13+
* 4. The result value is the missing no
14+
*
15+
* Formula for Calculate sum of 1 to N
16+
* 1 + 2+ 3 + 4 + 5 + ...... + N
17+
* sum = (N * (N+1)) / 2
18+
*
19+
* array = {2, 4, 1, 6, 7, 5, 3, 9};
20+
* array Length = 8
21+
* sum of array = 37
22+
* N = array Length + 1 (missing no) = 9
23+
* sum of 1 to N = 45
24+
* missing no = sum of 1 to N - array sum
25+
* missing no = 45 - 37
26+
*
27+
* Note::
28+
* This approach will work only for array contains
29+
* value from 1 to n (order does not matter)
30+
*/
31+
public class FindMissingNo {
32+
public static void main(String[] args) {
33+
// int array[] = {2, 4, 1, 6, 7, 5, 3, 9};
34+
int array[] = {2, 4, 1, 6, 3};
35+
int n = array.length;
36+
37+
//calculate the sum of array
38+
int arraySum = 0;
39+
for(int v : array)
40+
arraySum += v;
41+
42+
//array length is 8
43+
//one no is missing, then n should by n+1
44+
// here 8+1
45+
n = n+1;
46+
47+
//this calculates the sum from 1 to (n).
48+
//1+2+3+....n
49+
int expectedSum = (n * (n+1)) / 2;
50+
51+
System.out.println("The Given Array is : ");
52+
for(int v : array)
53+
System.out.print(v+" ");
54+
55+
int missingNo = expectedSum - arraySum;
56+
System.out.println("\nMissing Number is : "+missingNo);
57+
}
58+
}
59+
/*
60+
OUTPUT
61+
62+
The Given Array is :
63+
2 4 1 6 7 5 3 9
64+
Missing Number is : 8
65+
66+
The Given Array is :
67+
2 4 1 6 3
68+
Missing Number is : 5
69+
*/

0 commit comments

Comments
 (0)