I'm working on a beginner question that checks if one array is the subset of another array, and I got stuck on one special case, here is the case example: a = [1,2,3]
, b = [1,1]
, in which a
contains 1
, b
only contains 1
, but b
is not a subset of a
because b
contains two of 1
s.
How can I modify my code to have it check this special case?
Below is the code snippet:
// True if one array is the subset of another array
public boolean checkSubset(int[] arr1, int[] arr2) {
// A counter to remember how many
// times the same element is found
int cnt = 0;
// If one of the array is empty, for empty set
if (arr1.length == 0 || arr2.length == 0) {
return true;
}
// Compare elements in two arrays
for (int i = 0; i < arr1.length; ++i) {
for (int j = 0; i < arr2.length; ++j) {
if (arr1[i] == arr2[j]) {
++cnt;
break;
}
}
}
// cnt would equal to the length of arr1 or arr2
// if one array is the subset of the other one
return (cnt == arr1.length || cnt == arr2.length);
}