my dsa gallery
ArrayTwo Pointers / Merge Process

Union of Two Sorted Arrays

Problem link: https://www.geeksforgeeks.org/problems/union-of-two-sorted-arrays-1587115621/1

Problem Statement

Given two sorted arrays a[] and b[], find the union of these two arrays. The union of two arrays can be defined as the set containing distinct elements from both arrays. The elements in the union should be in sorted order.

Input

Two sorted integer arrays a[] and b[].

Output

An ArrayList of integers representing the union of the two arrays in sorted order.

Example

Input: a[] = [1, 2, 3, 4, 5], b[] = [1, 2, 3, 6, 7] Output: [1, 2, 3, 4, 5, 6, 7] Explanation: Distinct elements from both arrays are 1, 2, 3, 4, 5, 6, 7.

Explanation

We combine elements from both arrays. Elements like 1, 2, and 3 appear in both but are only included once in the result to maintain 'distinct' property.

Brute Force

Intuition

Use a Set data structure (specifically a TreeSet to keep it sorted) to store all elements from both arrays. The set automatically handles duplicates.

Approach

  1. Initialize a TreeSet.
  2. Iterate through array a and add all elements to the set.
  3. Iterate through array b and add all elements to the set.
  4. Convert the set to a list and return.

Dry Run

a=[1,2], b=[2,3] Set: {1, 2} -> {1, 2, 3} Result: [1, 2, 3]

Code (Java)

import java.util.*;
class Solution {
    public static ArrayList<Integer> findUnion(int a[], int b[]) {
        TreeSet<Integer> set = new TreeSet<>();
        for (int x : a) set.add(x);
        for (int x : b) set.add(x);
        return new ArrayList<>(set);
    }
}
Time: O((N+M) log(N+M))Space: O(N+M)

Complexity Analysis

Adding elements to a TreeSet takes logarithmic time, and we do this for all elements in both arrays.

Optimal Solution

Intuition

Since the arrays are already sorted, we can use two pointers (one for each array). Compare the elements at both pointers, pick the smaller one, and move that pointer forward. To handle duplicates, only add the element if it is different from the last element added to the result.

Approach

  1. Initialize i = 0, j = 0 and an empty list union.
  2. While i < n and j < m:
    • If a[i] <= b[j]: Add a[i] to union (if not duplicate) and i++.
    • Else: Add b[j] to union (if not duplicate) and j++.
  3. Add remaining elements from array a or b while checking for duplicates.
  4. Return union.
Step 1 of 2- Pointer Comparison
Compare 1 and 1. Add 1, increment both pointers to skip identical values.
Loading...
Use arrow keys to navigate

Dry Run

a=[1,2,3], b=[2,4]

  1. i=0, j=0: 1 < 2. Add 1. i=1.
  2. i=1, j=0: 2 == 2. Add 2. i=2, j=1.
  3. i=2, j=1: 3 < 4. Add 3. i=3.
  4. Array a exhausted. j=1: Add 4. j=2. Result: [1, 2, 3, 4]

Code (Java)

Time: O(N + M)Space: O(1)

Complexity Analysis

We traverse both arrays exactly once. The space complexity is O(1) if we don't count the space required for the output list.

Quick Revision (Brute Force)

  • Use TreeSet for uniqueness and sorting
  • O((N+M) log (N+M)) time

Quick Revision (Optimal)

  • Two-Pointer merge strategy
  • Compare a[i] and b[j]
  • Add smaller value and check for duplicates with previous entry
  • O(N+M) time, O(1) extra space

Study Photos

Upload screenshots/notes for this specific problem.

Drag & drop or click to select
Drop an image anywhere in this box to upload.
No photos uploaded till now.

Comments

Stored in D1. Login required.
No comments yet.