Skip to content

Commit d7b1395

Browse files
solution of All missing number added
1 parent d2c3978 commit d7b1395

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

LeetCode/AllMissingNumber.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.util.ArrayList;
2+
3+
public class AllMissingNumber { // Question: Find all missing number in the array in O(log n) timeComplexity
4+
public static void main(String[] args) {
5+
6+
int[] arr = {2, 1, 3, 6, 4, 9, 5, 3, 2};
7+
8+
System.out.println(missingNumber(arr));
9+
}
10+
11+
// method to sort the array using cyclic sort and to find missing number
12+
public static ArrayList<Integer> missingNumber(int[] arr) { // Here we use ArrayList because we don`t know how many numbers are missing
13+
14+
int i = 0;
15+
while (i < arr.length) {
16+
17+
int index = arr[i] - 1;
18+
19+
if(arr[i] != arr[index]) {
20+
21+
swap(arr, i, index);
22+
}else {
23+
24+
i++;
25+
}
26+
}
27+
28+
// Finding missing number
29+
ArrayList<Integer> nums = new ArrayList<>();
30+
for (int j = 0; j < arr.length; j++) {
31+
32+
if(arr[j] != j + 1) {
33+
34+
nums.add(j + 1); // Adding the numbers into the list
35+
}else {
36+
37+
j++;
38+
}
39+
}
40+
return nums;
41+
}
42+
43+
// Method to swap the numbers
44+
public static void swap(int[] arr, int first, int second) {
45+
46+
int temp = arr[first];
47+
arr[first] = arr[second];
48+
arr[second] = temp;
49+
}
50+
}

0 commit comments

Comments
 (0)