Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I tried to make a program that will check if an an array contains all the array values from another array. So, if that's true, the program will return 1 using a value for it. If it isn't true, it will return 0(I named it p). I failed to make that program though. Could you please help me?

share|improve this question
4  
What have you tried so far? edit your question and include some code –  xkickflip Apr 4 '13 at 20:57
1  
Hint: If both arrays were sorted, how could you test easily whether one contains the other? –  Zeta Apr 4 '13 at 21:16

1 Answer 1

#include <stdio.h>

int isSubset(int arr1[], int arr2[], int m, int n)
{
    int i = 0;
    int j = 0;
    for (i=0; i<n; i++)
    {
        for (j = 0; j<m; j++)
        {
           if(arr2[i] == arr1[j])
              break;
        }

        /* If the above inner loop was not broken at all then
           arr2[i] is not present in arr1[] */
        if (j == m)
           return 0;
    }

    /* If we reach here then all elements of arr2[] 
      are present in arr1[] */
    return 1;
}

int main()
{
    int arr1[] = {11, 1, 13, 21, 3, 7};
    int arr2[] = {11, 2, 7, 1};

    int m = sizeof(arr1)/sizeof(arr1[0]);
    int n = sizeof(arr2)/sizeof(arr2[0]);

    if(isSubset(arr1, arr2, m, n))
      printf("arr2[] is subset of arr1[] ");
    else
      printf("arr2[] is not a subset of arr1[]");      

    getchar();
    return 0;
}



Ideone Link up and running : http://ideone.com/4u9oQm

share|improve this answer
    
Time Complexity: O(m*n) –  Saurabh Rana Sep 16 '13 at 16:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.