Given two integer arrays nums1 and nums2, return a list containing two lists: the union and the intersection of the two arrays.
The union contains all distinct elements present in either array. The intersection contains all distinct elements present in both arrays. Each element in the result should appear only once.
Return the union as the first list and the intersection as the second list. Both lists should be sorted in ascending order.
Function Signature
def union_and_intersection(nums1: list[int], nums2: list[int]) -> list[list[int]]:
Rules
-
Return exactly two lists,
[union, intersection]
, in that order.
-
Each list holds distinct values sorted in ascending numeric order.
-
Duplicates inside either input do not change the result.
-
When the arrays share no value, the intersection is an empty list
[]
.
-
The input arrays are not guaranteed to be sorted.
Constraints
-
1 <= len(nums1), len(nums2) <= 10^4
-
-10^9 <= nums1[i], nums2[i] <= 10^9
Examples
Input: nums1 = [1,2,3,4,5], nums2 = [3,4,5,6,7]
Output: [[1,2,3,4,5,6,7],[3,4,5]]
Every value from 1 to 7 appears in at least one array, so all seven are in the union. Only 3, 4 and 5 appear in both arrays.
Input: nums1 = [1,2,2,3], nums2 = [2,2,4]
Output: [[1,2,3,4],[2]]
The distinct values are 1, 2, 3 and 4. The value 2 is the only one present in both arrays, and it appears once in the intersection even though each array holds it twice.
Input: nums1 = [-3,0,-3], nums2 = [5,1]
Output: [[-3,0,1,5],[]]
The arrays share no value, so the intersection is empty. The union is sorted numerically, so the negative value comes first.