AlgoInsight

DSA problem

Intersection of Two Arrays

EasyArraysPattern: Hash MapbeginnerFreeAmazonMeta

Given two arrays, find their intersection - the elements that appear in both. Each element in the result should appear as many times as it shows in both arrays.

The hash map approach is optimal: build a frequency map from the first array, then iterate through the second array. For each element, if it exists in the map with count greater than 0, add it to the result and decrement the count. This handles duplicates correctly in O(M + N) time.

An alternative for sorted arrays uses two pointers, advancing the smaller side and recording equal elements. This is a building block for merging intervals, finding common elements across arrays, and database joins.

Examples

Example 1
Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Output: [2, 2]
Explanation: 2 appears twice in nums1 and twice in nums2, so it appears twice in the intersection.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

array

Browse all DSA problems