forked from super30admin/Array-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem1.java
More file actions
51 lines (32 loc) · 1.03 KB
/
Problem1.java
File metadata and controls
51 lines (32 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//We use a HashSet to track numbers present in the array.
//Steps:
//1.Add all elements into HashSet
//2.Check numbers from 1 to n
//3.If number is missing in set → add to result
//Time: O(n)
//Space: O(n)
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
// List to store missing numbers
List<Integer> result = new ArrayList<>();
// HashSet to store all present numbers
HashSet<Integer> set = new HashSet<>();
// Length of array
int n = nums.length;
// Step 1: Add all numbers from array into HashSet
// This helps in fast lookup O(1)
for(int i = 0; i < n; i++) {
set.add(nums[i]);
}
// Step 2: Check numbers from 1 to n
for(int i = 1; i <= n; i++) {
// If number is not present in set
// then it is missing
if(!set.contains(i)) {
result.add(i);
}
}
// Return missing numbers list
return result;
}
}