Hone logo
Hone
Problems

Finding Common Ground: Array Intersection

This challenge focuses on a fundamental operation in programming: finding the intersection of two arrays. The intersection of two arrays is a new array containing only the elements that are present in both of the original arrays. This is a common task in data analysis, database operations, and algorithm design.

Problem Description

Your task is to write a Javascript function that takes two arrays of numbers as input and returns a new array containing their intersection. The order of elements in the output array does not matter. Each element in the result should be unique, even if it appears multiple times in either of the input arrays.

Requirements:

  • The function should accept two arrays, nums1 and nums2, as arguments.
  • The function should return a new array containing only the elements that exist in both nums1 and nums2.
  • Each element in the returned array must be unique.
  • The order of elements in the returned array does not matter.

Edge Cases to Consider:

  • Empty input arrays.
  • Arrays with no common elements.
  • Arrays with duplicate elements.

Examples

Example 1:

Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Output: [2]
Explanation: The only number that appears in both arrays is 2.

Example 2:

Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]
Output: [4, 9]
Explanation: The numbers 4 and 9 appear in both arrays. The duplicates in nums2 do not affect the uniqueness of the output.

Example 3:

Input: nums1 = [1, 2, 3], nums2 = [4, 5, 6]
Output: []
Explanation: There are no common elements between the two arrays.

Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000
  • The input arrays can contain duplicate numbers.
  • Your solution should aim for a time complexity of O(n + m) or better, where n and m are the lengths of the input arrays.

Notes

Consider how you can efficiently check for the presence of elements from one array within another. Data structures like Sets can be very helpful here. Remember that the output must contain unique elements.

Loading editor...
javascript