20(April) Union of Two Sorted Arrays
20. Union of Two Sorted Arrays
The problem can be found at the following link: Question Link
Problem Description
Given two sorted arrays of size ( n ) and ( m ) respectively, find their union. The Union of two arrays can be defined as the common and distinct elements in the two arrays.
Example:
Input:
n = 5, arr1[] = {1, 2, 3, 4, 5}
m = 5, arr2 [] = {1, 2, 3, 6, 7}Output:
1 2 3 4 5 6 7Explanation: Distinct elements including both arrays are: 1 2 3 4 5 6 7.
My Approach
Initialization:
Create a vector
ansto store the union of the two arrays.Sort both input arrays
arr1andarr2.
Union Calculation:
Initialize two pointers
iandjto traversearr1andarr2respectively.Compare elements at
arr1[i]andarr2[j].If
arr1[i]is less thanarr2[j], pusharr1[i]to theansvector and incrementi.If
arr1[i]is greater thanarr2[j], pusharr2[j]to theansvector and incrementj.If both are equal, push either to the
ansvector and increment bothiandj.
Continue this process until both arrays are completely traversed.
Remove Duplicates:
After merging, there may be duplicate elements in the
ansvector. Remove duplicates using theuniquefunction.
Return:
Return the
ansvector containing the union of the two arrays.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n + m), where ( n ) and ( m ) are the sizes of the two input arrays, as we traverse both arrays once.
Expected Auxiliary Space Complexity: O(n + m), as we use a vector to store the union of the two arrays.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated