Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000This approach utilizes hash sets to efficiently track and identify unique intersections between the two arrays. By converting one of the arrays into a set, we can check for existence of elements in constant time, and we store intersections in another set to ensure uniqueness.
This C solution uses a simple hash set implementation to find intersections. The set is represented by an array, and a naive hash function is used. It handles collisions with linear probing. Two sets are used: one for storing unique elements of nums1, and another for the results.
C++
Java
Python
C#
JavaScript
Time complexity is O(n + m) for inserting and checking elements, with n and m being the sizes of nums1 and nums2 respectively. Space complexity is O(n + m) for the two sets used.
This approach sorts both arrays and uses two pointers to identify the intersection. The sorted order ensures that we can efficiently find common elements in a single pass through both arrays.
This C solution sorts both arrays and uses two pointers to traverse them. The pointers move forward when differences are found, and add elements to the result only if they are equal and haven't been added before, ensuring uniqueness.
C++
Java
Python
C#
JavaScript
Time complexity is O(n log n + m log m) due to sorting, where n and m are the sizes of nums1 and nums2. Space complexity is O(n + m) for storing the sorted arrays.
| Approach | Complexity |
|---|---|
| Using Hash Sets | Time complexity is O(n + m) for inserting and checking elements, with n and m being the sizes of nums1 and nums2 respectively. Space complexity is O(n + m) for the two sets used. |
| Using Sorting and Two Pointers | Time complexity is O(n log n + m log m) due to sorting, where n and m are the sizes of nums1 and nums2. Space complexity is O(n + m) for storing the sorted arrays. |
Rotate Array by K places | Union, Intersection of Sorted Arrays | Move Zeros to End | Arrays Part-2 • take U forward • 1,241,841 views views
Watch 9 more video solutions →Practice Intersection of Two Arrays with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor