Saturday, December 28, 2024
Google search engine
HomeLanguagesPhp Program to Print uncommon elements from two sorted arrays

Php Program to Print uncommon elements from two sorted arrays

Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted 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.
 

PHP




<?php
// PHP program to find uncommon
// elements of two sorted arrays
 
function printUncommon($arr1, $arr2,
                       $n1, $n2)
{
    $i = 0;
    $j = 0;
    $k = 0;
    while ($i < $n1 && $j < $n2)
    {
 
        // If not common, print smaller
        if ($arr1[$i] < $arr2[$j])
        {
            echo $arr1[$i] . " ";
            $i++;
            $k++;
        }
        else if ($arr2[$j] < $arr1[$i])
        {
            echo $arr2[$j] . " ";
            $k++;
            $j++;
        }
 
        // Skip common element
        else
        {
            $i++;
            $j++;
        }
    }
 
    // printing remaining elements
    while ($i < $n1)
    {
        echo $arr1[$i] . " ";
        $i++;
        $k++;
    }
    while ($j < $n2)
    {
        echo $arr2[$j] . " ";
        $j++;
        $k++;
    }
}
 
// Driver code
$arr1 = array(10, 20, 30);
$arr2 = array(20, 25, 30, 40, 50);
 
$n1 = sizeof($arr1) ;
$n2 = sizeof($arr2) ;
 
printUncommon($arr1, $arr2, $n1, $n2);
 
// This code is contributed by Anuj_67
?>


Output : 

10 25 40 50

 

Time Complexity: O(n1 + n2), where n1 and n2 represents the size of the given two arrays.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Please refer complete article on Print uncommon elements from two sorted arrays for more details!
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments