Intersection of Two Arrays II

easy

Find intersection of two arrays including duplicates

Intersection of Two Arrays II

Key Insight

Sort both arrays. Equal elements → add to result and advance both. Otherwise advance the smaller pointer.

Step 1Sort Both
nums2: [2, 2]
i
j
1
0
1
1
2
2
2
3
same direction

Sort both arrays. nums1=[1,1,2,2], nums2=[2,2]. Use two pointers.

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Intersection of Two Arrays II

Sort both arrays. Equal elements → add to result and advance both. Otherwise advance the smaller pointer.

  1. Sort Both

    Sort both arrays. nums1=[1,1,2,2], nums2=[2,2]. Use two pointers.

  2. Advance Smaller

    i=0: nums1[0]=1 < nums2[0]=2. Advance i.

  3. Still Smaller

    i=1: nums1[1]=1 < nums2[0]=2. Advance i again.

  4. Match Found

    i=2: nums1[2]=2 == nums2[0]=2. Match! Add 2. Both advance. Then 2==2 again.

  5. Result

    Intersection with duplicates preserved: [2, 2].