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.
Examples:
Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1}
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[]
http://www.geeksforgeeks.org/find-whether-an-array-is-subset-of-another-array-set-1/
Method 2:Sorting and Binary Search
a) If the element is not found then return 0.
3) If all elements are present then return 1.
Time Complexity: O(mLogm + nLogm) If an mLogm algorithm is used for sorting which is not the case in above code. In above code Quick Sort is sued and worst case time complexity of Quick Sort is O(m^2)
2) Use Merge type of process to see if all elements of sorted arr2[] are present in sorted arr1[].
Time Complexity: O(mLogm + nLogn)
Note that method 1, method 2 don’t handle the cases when we have duplicates in arr2[]. For example, {1, 4, 4, 2} is not a subset of {1, 4, 2}, but these methods will print it as a subset >Method of merging handles all cases.
Examples:
Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1}
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[]
http://www.geeksforgeeks.org/find-whether-an-array-is-subset-of-another-array-set-1/
Method 1:Two Loops:O(n2)
Use two loops: The outer loop picks all the elements of arr2[] one by one. The inner loop linearly searches for the element picked by outer loop. If all elements are found then return 1, else return 0.
1) Sort arr1[] O(mLogm)
2) For each element of arr2[], do binary search for it in sorted arr1[].a) If the element is not found then return 0.
3) If all elements are present then return 1.
Time Complexity: O(mLogm + nLogm) If an mLogm algorithm is used for sorting which is not the case in above code. In above code Quick Sort is sued and worst case time complexity of Quick Sort is O(m^2)
Method 3:Sorting and Merging
1) Sort both arrays: arr1[] and arr2[] O(mLogm + nLogn)2) Use Merge type of process to see if all elements of sorted arr2[] are present in sorted arr1[].
Time Complexity: O(mLogm + nLogn)
Note that method 1, method 2 don’t handle the cases when we have duplicates in arr2[]. For example, {1, 4, 4, 2} is not a subset of {1, 4, 2}, but these methods will print it as a subset >Method of merging handles all cases.
No comments:
Post a Comment