Norway


Given two of distinct , we need to those from both that are not common. The output should be printed in order.

Examples:

Input : arr1[] = {10, 20, 30}
        arr2[] = {20, 25, 30, 40, 50}
Output : 10 25 40 50
We do not print 20 and 30 as these
elements are present in both arrays.

Input : arr1[] = {10, 20, 30}
        arr2[] = {40, 50}
Output : 10 20 30 40 50
        

The idea is based on merge process of merge sort. We traverse both arrays and skip common elements.

// C++ program to find  elements of
// two sorted arrays
#include <iostream>
using namespace std;

void printUncommon(int arr1[], int arr2[], 
                           int n1, int n2)
{

    int i = 0, j = 0, k = 0;
    while (i < n1 && j < n2) {

        // If not common, print smaller
        if (arr1[i] < arr2[j]) {
            cout << arr1[i] << " ";
            i++;
            k++;
        }
        else if (arr2[j] < arr1[i]) {
            cout << arr2[j] << " ";
            k++;
            j++;
        }

        // Skip common element
        else {
            i++;
            j++;
        }
    }

    // printing remaining elements
    while (i < n1) {
        cout << arr1[i] << " ";
        i++;
        k++;
    }
    while (j < n2) {
        cout << arr2[j] << " ";
        j++;
        k++;
    }
}

// Driver 
int main()
{
    int arr1[] = {10, 20, 30};
    int arr2[] = {20, 25, 30, 40, 50};
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
    printUncommon(arr1, arr2, n1, n2);
    return 0;
}

- avatar - Print uncommon elements from two sorted arrays

If you like GeeksforGeeks and would like to contribute, you can also write an using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here