×

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

Fahrenheit to Celsius in C

Before going into conversion, we have to know what Fahrenheit and Celsius mean, these are both units to measure the temperature.In our daily life, we use both Fahrenheit and Celsius,...

1 minute read.

Fee Management System in C

The concept is to split every operation into its very own characteristic. Software is made from all of the capabilities mixed with transfer cases. An example of the capabilities may...

5 minutes read.

Selection sort in C

In the C standard, the selection sorting technique exists where the smallest among the unsorted elements of the array is selected at each time and is then inserted into its...

3 minutes read.

String Handling functions in C

String :- The String is the collection of characters. Every String ends with the null character, and the String is enclosed in the double quotations .ie, "javaTpoint". If we see any...

5 minutes read.

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

Nested Loops in C Programming Examples

A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a “loop inside the...

6 minutes read.

Local Labels in C

Anyone who has written programs in the C programming language is required to be familiar with the "go to" and "labels" used in C to navigate between functions. "Local labels"...

4 minutes read.

Float in islower() in C

Introduction: This article briefly discusses the float in islower() in C. The islower() function checks if the input character passed inside the function is lowercase. Lowercase letters include (a-z). The islower()...

4 minutes read.

Int in C

The keyword int in C programming stands for integer and it is a data type which is used for variable declarations or declaration of functions of different types. Similar to...

4 minutes read.

Unformatted input() and output() function in C

Unformatted Input and Output functions take the character, character array, and strings as input. We can read-only character data types with these functions. These functions are already defined in the...

5 minutes read.

Difference between while and do-while loop in C

Introduction Both 'While' and 'Do-While' loops in C mostly have a similar concept, and the code of both loops runs for mainly similar purposes. Both loops process the program/code in the...

3 minutes read.

Loop Questions in C

Question 1: What is For loop syntax? Ans: The syntax that has been used for the ‘for’ loop in C programming language is: for (initialization statement /*for providing a value to variables*/; test...

19 minutes read.

Pascal Triangle in C

The pascal triangle in c is an array of binomial coefficients in triangular form. Here the nth row contains the binomial coefficient of ncr.In a pascal triangle, every number is...

2 minutes read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

While Loop Syntax in C

What is Loop? The statements in the sequence are repeatedly executed via looping statements in C until the condition is met. The body of a loop and a control statement make...

4 minutes read.

Armstrong Number in C

The Armstrong number is defined as the sum of each of its digits to the power of the number base for the each given number with any given number base....

3 minutes read.

FIFO Example in the C Language

FIFO is an acronym that means "First In, First Out." It is a data structure handling method in which the first element is handled first, and the last element is...

3 minutes read.

Fseek Function in C

The fseek function is a function in the C standard library that changes the position of the file pointer in a stream-oriented file. It is typically used to move the...

3 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.