×

Find Union and Intersection of Two Arrays in C

Union

You can find the union of the two sorted arrays using the join merge method on arr1[] and arr2[].

  • Use two index variables i and j with initial values i = 0 and j = 0.
  • If arr1[i] is less than arr2[j], output arr1[i] and increment i.
  • If arr1[i] is greater than arr2[j], print arr2[j] and increment j.
  • If both are equal, print one or the other and increment both i and j.
  • print the rest of the elements.

For example:

#include <stdio.h>
/* Function prints union of arr1[] and arr2[]
   m is the number of elements in arr1[]
   n is the number of elements in arr2[] */
void printUnion(int arr1[], int arr2[], int m, int n)   {
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            printf(" %d ", arr1[i++]);
        else if (arr2[j] < arr1[i])
            printf(" %d ", arr2[j++]);
        else {
            printf(" %d ", arr2[j++]);
            i++;   }   }
    /* Print remaining elements of the larger array */
    while (i < m)
        printf(" %d ", arr1[i++]);
    while (j < n)
        printf(" %d ", arr2[j++]);  }
int main()  {
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
    printUnion(arr1, arr2, m, n);
    getchar();
    return 0;  }


Output:

1 2 3 4 5 6 7

Time Complexity: O(m + n)

Auxiliary Space: O(1)

Handling duplicates in one of the arrays:

The code above does not handle duplicates in any array. To deal with duplicates, check each element to see if its adjacent elements are the same.

// C program for the above approach
#include <stdio.h>
#include <string.h>
static void UnionArray(int arr1[], int arr2[], int l1, int l2)  {
    // Taking max element present in either array
    int m = arr1[l1 - 1];
    int n = arr2[l2 - 1];
    int ans = 0;
    if (m > n)
        ans = m;
    else
        ans = n;
    // Finding elements from 1st array (non duplicates
    // only). Using another array for storing union elements
    // of both arrays Assuming max element present in array
    // is not more than 10^7
    int newtable[ans + 1];
    for (int i = 0; i < ans + 1; i++)
        newtable[i] = 0;
    // First element is always present in final answer
    printf("%d ", arr1[0]);


// Incrementing the First element's count in it's
    // corresponding index in newtable
    ++newtable[arr1[0]];
    // Starting traversing the first array from 1st index
    // till last
    for (int i = 1; i < l1; i++) {
        // Checking whether current element is not equal to
        // it's previous element
        if (arr1[i] != arr1[i - 1]) {
            printf("%d ", arr1[i]);
            ++newtable[arr1[i]]; }  }
    // Finding only non common elements from 2nd array
    for (int j = 0; j < l2; j++) {
        // By checking whether it's already resent in
        // newtable or not
        if (newtable[arr2[j]] == 0) {
            printf("%d ", arr2[j]);
            ++newtable[arr2[j]]; }   }   }


// Driver Code
int main()   {
    int arr1[] = { 1, 2, 2, 2, 3 };
    int arr2[] = { 2, 3, 4, 5 };
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int m = sizeof(arr2) / sizeof(arr2[0]);
    UnionArray(arr1, arr2, n, m);
    return 0;
}


Output:

1 2 3 4 5

Intersection

The intersection of the arr1 and arr2 arrays you can use the following method to find the intersection of two permuted arrays.

  • Use two index variables i and j with initial values i = 0 and j = 0.  
  • If arr1[i] is less than arr2[j], increment i.
  • Increase j if arr1[i] is greater than arr2[j].
  • Print one of these, and if i and j are the same, increment both.

For example:

#include <stdio.h>


/* Function prints Intersection of arr1[] and arr2[]
   m is the number of elements in arr1[]
   n is the number of elements in arr2[] */
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;


while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr2[j] < arr1[i])
            j++;
        else /* if arr1[i] == arr2[j] */
        {
            printf(" %d ", arr2[j++]);


            i++;
        }
    }
}
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
    printIntersection(arr1, arr2, m, n);
    getchar();
    return 0;
}

Output:

2  5

Handling duplicates with arrays:

The code above does not handle arrays with duplicate elements. Duplicate elements should not be counted at intersections. To handle the copy, check if there is a continuous component in the convergence list. An implementation of this strategy is shown below.

// C++ program to find intersection of two sorted arrays
#include <bits/stdc++.h>
using namespace std;
/* Function prints Intersection of arr1[] and arr2[]
m is the number of elements in arr1[]
n is the number of elements in arr2[] */
void print_intersection(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;
    set<int> s;  //set for handling duplicate elements in intersection list
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr2[j] < arr1[i])


            j++;
        else /* if arr1[i] == arr2[j] */
        {
            s.insert(arr2[j]);   //insertion in set s
            i++;
            j++;   }   }
    for(auto itr: s)  //printing intersection set list
    {
        cout<<itr<<" ";
        }       }
/* Driver code */
int main()
{


    int arr1[] = { 1, 2, 2, 3, 4 };
    int arr2[] = { 2, 2, 4, 6, 7, 8 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
    // Function calling
    print_intersection(arr1, arr2, m, n);
    return 0;
}

Output:

2 4

Related Topics

How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps. Take each character from...

3 minutes read.

C program to find factorial of a number using Recursion

What does the term "Factorial of a Number" mean? In mathematics, factorial is the product of all positive integers that are less than or equal to a certain positive integer, and...

2 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Pure Virtual Function in C

Before knowing about the pure virtual function some of the important points about the virtual function in C++ are given below. In c++ the member function that is defined in the...

4 minutes read.

Factorial Program in C Using While Loop

Before looking into the mechanism of factorial program, first, you have to understand about the working of a while loop. While Loop The syntax that has been used for the “while” loop...

4 minutes read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

Snake Game in C

Snake game in C is basic desktop console program which was created in 1970’s. It is an old classic game which was played by every child across the world. This...

4 minutes read.

C and C++ Binary Files

What is a binary file? A file in which the content is written in binary format is called a binary file. A binary file is not a text file. There are...

7 minutes read.

Banker’s Algorithm in C

Introduction Before doing a "s-state" check to look for potential activities and deciding if allocation should be allowed to continue, the banker's algorithm, a resource allocation and deadlock avoidance algorithm, tests...

5 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

Math functions in C

Math functions in C: In the C programming language, the compiler allows the developer to perform mathematical operations through the header’s functions, represented by <math.h>. The <math.h> header defines various mathematical...

3 minutes read.

How to create a node in C?

A node is a small concept taken from the graph theory, or a node is a fundamental unit of a data structure, like a tree data structure. Every graph contains...

3 minutes read.

Run Time Polymorphism in C

What is polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. An individual who can have...

4 minutes read.

How to lock top row in Excel

How to lock top row in excel While working with an Excel spreadsheet, the user utilizes the rows and columns to enter the details under various headings. Sometimes while scrolling the...

4 minutes read.

Bit Stuffing Program in C

What is a Bit Stuffing? The process of inserting one or more extra bits (0) into data is known as bit stuffing. To provide signalling information to a recipient, these are...

3 minutes read.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

Exponential() in C

Introduction: In C language, there are available many types of functions. The exponential() function is one of them. It is a mathematical function. This article describes using the pow() property to...

3 minutes read.

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

Structure in C

Why Structure came into the picture? In the actual world, we deal with entities that are collections of objects rather than tiny bits of data like integers, characters, floats, etc. So,...

4 minutes read.

How to include graphics.h in C?

How to include graphics.h in code blocks? Graphics .h is a header that allows drawing lines, rectangles, ovals, arcs, polygons, pictures, and strings on a graphical window by giving access to...

6 minutes read.