Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
K-th Element of Merged Two Sorted Arrays
Next article icon

Symmetric difference of two sorted array

Last Updated : 19 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

There are two sorted array arr1 and arr2. We have to find the symmetric difference of Aarr1 and arr2. Symmetric Difference basically contains all elements of two arrays except common elements. 

Symmetric difference of two array is the all  array elements of both array except the elements  that are presents in both array. SymmDiff = (arr1 - arr2) UNION (arr2 - arr1).                 OR SymmDiff = (arr1 UNION arr2) - (arr1 INTERSECTION arr2).

Examples:  

Input : arr1[] = {2, 4, 5, 7, 8, 10, 12, 15}.         arr2[] = {5, 8, 11, 12, 14, 15}. Output : 2 4 7 10 11 14                 arr1[] - arr2[] = {2, 4, 7, 10}.         arr[2] - arr1[] = {11, 14}.         SymmDiff = (arr1[] - arr2[]) UNION                     (arr2[] - arr1[]).                  = {2, 4, 7, 10, 11, 14}.   Input : arr1[] = {1, 3, 5, 8, 15, 27, 35}.         arr2[] = {5, 7, 8, 11, 15, 18, 35}. Output : 1 3 7 11 18 27         arr1[] - arr2[] = {1, 3, 27}.         arr[2] - arr1[] = {7, 11, 18}.         SymmDiff = (arr1[] - arr2[]) UNION                     (arr2[] - arr1[]).                  = {1, 3, 7, 11, 18, 27}.

A Simple Solution is to traverse through both arrays one by one. For every element of one array, check if it is present in other array. If yes, then ignore it, else print it. Time complexity of this solution is O(n*n).

An Efficient solution for finding the symmetric difference of two sorted arrays is similar to merge process of merge sort. We traverse both arrays simultaneously and print smaller elements if current two elements do not match and move ahead in array with smaller element. Else we ignore the elements and move ahead in both arrays. 

Implementation:

C++




// C++ program to find the symmetric difference
// of two sorted array.
#include <iostream>
using namespace std;
void symmDiff(int arr1[], int arr2[], int n, int m)
{
    // Traverse both arrays simultaneously.
    int i = 0, j = 0;
    while (i < n && j < m) {
       
        // Print smaller element and move
        // ahead in array with smaller element
        if (arr1[i] < arr2[j]) {
            cout << arr1[i] << " ";
            i++;
        }
        else if (arr2[j] < arr1[i]) {
            cout << arr2[j] << " ";
            j++;
        }
 
        // If both elements same, move ahead
        // in both arrays.
        else {
            i++;
            j++;
        }
    }
    while (i < n) {
        cout << arr1[i] << " ";
        i++;
    }
    while (j < m) {
        cout << arr2[j] << " ";
        j++;
    }
}
 
// Driver code
int main()
{
    int arr1[] = { 2, 4, 5, 7, 8, 10, 12, 15 };
    int arr2[] = { 5, 8, 11, 12, 14, 15 };
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int m = sizeof(arr2) / sizeof(arr2[0]);
    symmDiff(arr1, arr2, n, m);
 
    return 0;
}
 
 

Java




// Java program to find the symmetric
// difference of two sorted array.
import java.util.*;
class GFG {
    static void symmDiff(int[] arr1, int[] arr2, int n,
                         int m)
    {
        // Traverse both arrays simultaneously.
        int i = 0, j = 0;
        while (i < n && j < m) {
            // Print smaller element and move
            // ahead in array with smaller element
            if (arr1[i] < arr2[j]) {
                System.out.print(arr1[i] + " ");
                i++;
            }
            else if (arr2[j] < arr1[i]) {
                System.out.print(arr2[j] + " ");
                j++;
            }
 
            // If both elements same, move ahead
            // in both arrays.
            else {
                i++;
                j++;
            }
        }
        while (i < n) {
            System.out.print(arr1[i] + " ");
            i++;
        }
        while (j < m) {
            System.out.print(arr2[j] + " ");
            j++;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr1 = { 2, 4, 5, 7, 8, 10, 12, 15 };
        int[] arr2 = { 5, 8, 11, 12, 14, 15 };
        int n = arr1.length;
        int m = arr2.length;
        symmDiff(arr1, arr2, n, m);
    }
}
/* This code is contributed by Kriti Shukla */
 
 

Python3




# Python3 program to
# find the symmetric
# difference of two
# sorted array.
 
 
def symmDiff(arr1, arr2, n, m):
 
    # Traverse both arrays
    # simultaneously.
    i = 0
    j = 0
    while (i < n and j < m):
 
        # Print smaller element
        # and move ahead in
        # array with smaller
        # element
        if (arr1[i] < arr2[j]):
            print(arr1[i], end=" ")
            i += 1
 
        elif (arr2[j] < arr1[i]):
            print(arr2[j], end=" ")
            j += 1
 
        # If both elements
        # same, move ahead
        # in both arrays.
        else:
 
            i += 1
            j += 1
 
    while i < n:
        print(arr1[i], end=' ')
        i += 1
 
    while j < m:
        print(arr2[j], end=' ')
        j += 1
 
 
# Driver code
arr1 = [2, 4, 5, 7, 8, 10, 12, 15]
arr2 = [5, 8, 11, 12, 14, 15]
n = len(arr1)
m = len(arr2)
 
symmDiff(arr1, arr2, n, m)
 
# This code is contributed by Smitha Dinesh Semwal
 
 

C#




// C# program to find the symmetric
// difference of two sorted array.
using System;
 
class GFG {
 
    static void symmDiff(int[] arr1, int[] arr2, int n,
                         int m)
    {
 
        // Traverse both arrays simultaneously.
        int i = 0, j = 0;
 
        while (i < n && j < m) {
 
            // Print smaller element and move
            // ahead in array with smaller element
            if (arr1[i] < arr2[j]) {
                Console.Write(arr1[i] + " ");
                i++;
            }
            else if (arr2[j] < arr1[i]) {
                Console.Write(arr2[j] + " ");
                j++;
            }
 
            // If both elements same, move ahead
            // in both arrays.
            else {
                i++;
                j++;
            }
        }
        while (i < n) {
            Console.Write(arr1[i] + " ");
            i++;
        }
 
        while (j < m) {
            Console.Write(arr2[j] + " ");
            j++;
        }
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr1 = { 2, 4, 5, 7, 8, 10, 12, 15 };
        int[] arr2 = { 5, 8, 11, 12, 14, 15 };
        int n = arr1.Length;
        int m = arr2.Length;
 
        symmDiff(arr1, arr2, n, m);
    }
}
 
/* This code is contributed by vt_m*/
 
 

PHP




<?php
// PHP program to find the
// symmetric difference
// of two sorted array.
function symmDiff($arr1, $arr2,
                       $n, $m)
{
     
    // Traverse both arrays
    // simultaneously.
    $i = 0; $j = 0;
    while ($i < $n && $j < $m)
    {
         
        // Print smaller element
        // and move ahead in array
        // with smaller element
        if ($arr1[$i] < $arr2[$j])
        {
            echo($arr1[$i] . " ");
            $i++;
        }
        else if ($arr2[$j] < $arr1[$i])
        {
            echo($arr2[$j] . " ");
            $j++;
        }
 
        // If both elements same,
        // move ahead in both arrays
        else
        {
            $i++;
            $j++;
        }
    }
   
    while ($i < $n) {
        echo($arr1[$i] . " ");
        $i++;
    }
 
    while ($j < $m) {
        echo($arr2[$j] . " ");
        $j++;
    }
}
 
// Driver code
$arr1 = array(2, 4, 5, 7, 8, 10, 12, 15);
$arr2 = array(5, 8, 11, 12, 14, 15);
$n = sizeof($arr1);
$m = sizeof($arr2);
symmDiff($arr1, $arr2, $n, $m);
 
// This code is contributed by Ajit.
?>
 
 

Javascript




<script>
 
    // Javascript program to find the symmetric
    // difference of two sorted array.
     
    function symmDiff(arr1, arr2, n, m)
    {
  
        // Traverse both arrays simultaneously.
        let i = 0, j = 0;
  
        while (i < n && j < m) {
  
            // Print smaller element and move
            // ahead in array with smaller element
            if (arr1[i] < arr2[j]) {
                document.write(arr1[i] + " ");
                i++;
            }
            else if (arr2[j] < arr1[i]) {
                document.write(arr2[j] + " ");
                j++;
            }
  
            // If both elements same, move ahead
            // in both arrays.
            else {
                i++;
                j++;
            }
        }
        while (i < n) {
            document.write(arr1[i] + " ");
            i++;
        }
  
        while (j < m) {
            document.write(arr2[j] + " ");
            j++;
        }
    }
     
    let arr1 = [ 2, 4, 5, 7, 8, 10, 12, 15 ];
    let arr2 = [ 5, 8, 11, 12, 14, 15 ];
    let n = arr1.length;
    let m = arr2.length;
 
    symmDiff(arr1, arr2, n, m);
     
</script>
 
 
Output
2 4 7 10 11 14 

Time Complexity: O(m + n).



Next Article
K-th Element of Merged Two Sorted Arrays
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Median of two Sorted Arrays of Different Sizes
    Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array. This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal s
    15+ min read
  • Sort given words as Array of Strings
    Given an array of strings Arr[]. The task is to sort them in lexicographic order. Examples: Input: Arr[] = {"sort", "this", "list"}Output: [list, sort, this] Input: Arr[] = {"sun", "earth", "mars", "mercury"}Output: [earth, mars, mercury, sun] Selection Sort Approach: The same problem can also be so
    15+ min read
  • set_symmetric_difference in C++ with Examples
    Symmetric difference of two sorted ranges The symmetric difference between two sets is formed by the elements that are present in one of the sets, but not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the existent order before the call. Th
    6 min read
  • K-th Element of Merged Two Sorted Arrays
    Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays. Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1
    15+ min read
  • Sum of middle elements of two sorted Arrays
    Given two sorted arrays, arr1[] and arr2[], each of size N, the task is to merge the arrays and find the sum of the two middle elements of the merged array. Example: Input: N = 5, arr1[] = {1,2,4,6,10}, arr2[] = {4,5,6,9,12}Output: 11Explanation: The merged array is {1,2,4,4,5,6,6,9,10,12}. The sum
    15 min read
  • Symmetric pairs in an array
    Given an array of pairs arr[], a pair (a, b) is said to be symmetric with (c, d) if b = c and a = d. In other words, reversing the elements of one pair should result in the other pair. The first element of each pair is guaranteed to be distinct. Examples: Input: arr[] = [[10, 20], [30, 40], [20, 10]
    15+ min read
  • Minimum sum of absolute difference of pairs of two arrays
    Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p
    7 min read
  • Reduce Array by replacing pair with their difference
    You are given an array of positive integers. You can perform the following operations on the array any number of times: Select the two largest elements in the array, suppose a and b.If a = b, remove both of them from the array.If a > b, remove b and the new value of a will be a-b or vice-versa.Th
    9 min read
  • Smallest Difference pair of values between two unsorted Arrays
    Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Examples : Input : A[] = {1, 3, 15, 11, 2} B[] = {23, 127, 235, 19, 8} Output : 3 That is, the pair (11, 8) Input : A[] = {10, 5, 40} B[] = {50, 90,
    11 min read
  • Merge Two Sorted Arrays Without Extra Space
    Given two sorted arrays a[] and b[] of size n and m respectively, the task is to merge both the arrays and rearrange the elements such that the smallest n elements are in a[] and the remaining m elements are in b[]. All elements in a[] and b[] should be in sorted order. Examples: Input: a[] = [2, 4,
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences