Array Intersection - Problem

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.

Note: You cannot use built-in set operations or hash maps for this problem.

Input & Output

Example 1 — Basic Intersection
$ Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
💡 Note: The only common element between both arrays is 2. Even though 2 appears multiple times, we return it only once.
Example 2 — Multiple Common Elements
$ Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
💡 Note: Both 4 and 9 appear in both arrays. The result can be in any order.
Example 3 — No Intersection
$ Input: nums1 = [1,2,3], nums2 = [4,5,6]
Output: []
💡 Note: No elements are common between the two arrays, so return empty array.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 1000

Visualization

Tap to expand
Array IntersectionFind Common ElementsINPUTnums1:1221nums2:22ALGORITHM1Sort both arrays2Use two pointers3Compare and collectSorted arrays:[1,2,2] [2,2]Pointers find match: 2RESULTCommon elements:[2]Unique intersectionKey Insight:Sorting enables efficient two-pointer traversal to find intersections in O(n log n) timeTutorialsPoint - Array Intersection | Sort and Two Pointers
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen