- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathArraySubset.java
More file actions
Latest commit
51 lines (45 loc) · 1.42 KB
/
Copy pathArraySubset.java
File metadata and controls
51 lines (45 loc) · 1.42 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
packageHashing;
importjava.util.HashSet;
importjava.util.Set;
/**
* @author kalpak
*
* Given two arrays: arr1[0..m-1] and arr2[0..n-1].
* Find whether arr2[] is a subset of arr1[] or not. Both the arrays are not in sorted order.
* It may be assumed that elements in both array are distinct.
*
* Examples:
*
* Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1}
* Output: arr2[] is a subset of arr1[]
*
* Input: arr1[] = {1, 2, 3, 4, 5, 6}, arr2[] = {1, 2, 4}
* Output: arr2[] is a subset of arr1[]
*
* Input: arr1[] = {10, 5, 2, 23, 19}, arr2[] = {19, 5, 3}
* Output: arr2[] is not a subset of arr1[]
*/
publicclassArraySubset {
publicstaticbooleanisSubset(int[] arr1, int[] arr2) {
Set<Integer> elements = newHashSet<>();
// put all the elements of arr1 into the
for(inti : arr1)
elements.add(i);
/*
now check if all the elements of arr2 is present or not.
if not, return false.
*/
for(inti : arr2) {
if(elements.contains(i) == false) returnfalse;
}
returntrue;
}
publicstaticvoidmain(String[] args) {
int[] arr1 = {11, 1, 13, 21, 3, 7};
int[] arr2 = {11, 3, 7, 1};
if(isSubset(arr1, arr2))
System.out.println("arr2 is a subset of arr1");
else
System.out.println("arr2 is not a subset of arr1");
}
}