|
U
Pro37. Union and Intersection of Two Sorted Arrays
Easy
Problem Description
Given two sorted arrays A (size N) and B (size M), find their sorted union (all distinct elements appearing in either) and intersection (all distinct elements appearing in both).
Input Format
- •Line 1: Two space-separated integers N and M (1≤N,M≤105).
- •Line 2: N sorted integers A1,…,AN.
- •Line 3: M sorted integers B1,…,BM.
Output Format
- •Line 1: Space-separated distinct integers in Union.
- •Line 2: Space-separated distinct integers in Intersection, or
EMPTYif intersection is empty.
Example 1:
Input:
5 4 1 2 2 3 4 2 2 4 6
Output:
1 2 3 4 6 2 4
Explanation: Union is {1, 2, 3, 4, 6}. Common elements are {2, 4}.
Example 2:
Input:
3 3 1 2 3 4 5 6
Output:
1 2 3 4 5 6 EMPTY
Explanation: Disjoint arrays have empty intersection.
Example 3:
Input:
2 2 5 5 5 5
Output:
5 5
Explanation: Only element 5 in both.
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
param_3 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit