CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Array Intersection
array
hashtable
sorting
# Array Intersection ## Difficulty Easy ## Tags `array`, `hash table`, `sorting` ## Problem Statement Given two integer arrays `nums1` and `nums2`, return an array of their intersection. Each element in the result must appear as many times as it shows in **both** arrays. You may return the result in any order. ## Constraints - 1 ≤ nums1.length, nums2.length ≤ 1000 - 0 ≤ nums1[i], nums2[i] ≤ 1000 ## Signatures ### Python ```python def intersect(nums1: List[int], nums2: List[int]) -> List[int]: pass ``` ### Java ```java public class Solution { public List<Integer> intersect(List<Integer> nums1, List<Integer> nums2) { return null; } } ``` ### Csharp ```csharp public class Solution { public IList<int> intersect(IList<int> nums1, IList<int> nums2) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: vector<int> intersect(vector<int> nums1, vector<int> nums2) { } }; ``` ### C ```c int* intersect(int* nums1, int* nums2) { } ``` ### Ruby ```ruby def intersect(nums1, nums2) end ``` ### Perl ```perl sub intersect { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def intersect(nums1: List[Int], nums2: List[Int]): List[Int] = { } } ``` ### Haskell ```haskell intersect :: ... -> ... intersect args = undefined ``` ### Clojure ```clojure (defn intersect [nums1 nums2] ) ``` ### Scheme ```scheme (define (intersect nums1 nums2) ) ``` ## Examples ### Example 1 **Input:** ``` nums1 = [1, 2, 2, 1] nums2 = [2, 2] ``` **Output:** ``` [2, 2] ``` **Explanation:** 2 appears twice in both arrays. ### Example 2 **Input:** ``` nums1 = [4, 9, 5] nums2 = [9, 4, 9, 8, 4] ``` **Output:** ``` [4, 9] or [9, 4] ``` **Explanation:** 4 and 9 each appear at least once in both. ### Example 3 **Input:** ``` nums1 = [1, 2, 3] nums2 = [4, 5, 6] ``` **Output:** ``` [] ``` **Explanation:** No common elements. ## Hints 1. **Hash Map approach**: Count occurrences in nums1, then iterate through nums2. If element exists with count > 0, add to result and decrement count. 2. **Sorting approach**: Sort both arrays, use two pointers to find common elements. 3. If one array is much smaller, iterate through the smaller one.
Login required
Please log in to view the solution editor and submit code.
Login
Register