Open In App

How to Find the Symmetric Difference of Two Deques in C++?

In C++, the symmetric difference between two deques is a set of all elements present in either of the deques but not in their intersection. In this article, we will learn how to find the symmetric difference of two deques in C++.

Example:

Input:
dq1 ={1,2,3,4,5}
dq2 ={3,4,5,6,7}

Output:
Symmetric Difference: 1 2 6  7

Find the Symmetric Difference of Two Deques in C++

To find the symmetric difference of two std::deques in C++, we can use the std::set_symmetric_difference() method provided by the STL library which finds the symmetric difference of the given two sorted ranges.

Syntax of std::set_symmetric_difference()

set_symmetric_difference(dq1.begin(), dq1.end(), dq2.begin(), dq2.end(), back_inserter(result));

where:

C++ Program to Find the Symmetric Difference of Two Deques

The below example demonstrates how to find the symmetric difference of two deques in C++ STL.

// C++ Program to illustrate how to find the symmetric
// difference of two deques
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // Initializing two deques
    deque<int> dq1 = { 10, 20, 30 };
    deque<int> dq2 = { 20, 30, 40 };

    // Sorting the deques
    sort(dq1.begin(), dq1.end());
    sort(dq2.begin(), dq2.end());

    // Finding the symmetric difference
    deque<int> dq_sym_diff;
    set_symmetric_difference(dq1.begin(), dq1.end(),
                             dq2.begin(), dq2.end(),
                             back_inserter(dq_sym_diff));

    cout << "Symmetric Difference = { ";
    for (int i : dq_sym_diff) {
        cout << i << " ";
    }
    cout << "}" << endl;

    return 0;
}

Output
Symmetric Difference = { 10 40 }

Time Complexity: O(NlogN + MlogN) where N and M are the number of elements in the deques.
Auxiliary Space: O(N + M)



Article Tags :