Skip to content

Instantly share code, notes, and snippets.

@PeculiarE
Last active March 4, 2026 23:26
Show Gist options
  • Select an option

  • Save PeculiarE/426e0cc84f352f1f4188ecc2f59b3f92 to your computer and use it in GitHub Desktop.

Select an option

Save PeculiarE/426e0cc84f352f1f4188ecc2f59b3f92 to your computer and use it in GitHub Desktop.
Intersection of Two Arrays II - LeetCode - Days 62 & 63

Question

Intuition

Approach

Complexity

  • Time complexity: $$O(n \log n + m \log m)$$

  • Space complexity: $$O(1)$$

Code

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1.sort()
        nums2.sort()

        output = []
        i, j = 0, 0

        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                output.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
            
        return output

Result

Screenshot 2026-03-03 at 22 11 02

Follow-Up Question: What if nums1's size is small compared to nums2's size? Which algorithm is better?

Intuition

Approach

Complexity

  • Time complexity: $$O(n + m)$$

  • Space complexity: $$O(m)$$, where $m$ is the size of the smaller array, $nums1$

Code

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # assuming  nums1's size is small compared to nums2's size
        nums1_tracker = {}
        for num in nums1:
            nums1_tracker[num] = nums1_tracker.get(num, 0) + 1
        
        output = []
        for num in nums2:
            if nums1_tracker.get(num, 0) > 0:
                output.append(num)
                nums1_tracker[num] -= 1
        
        return output

Result

Screenshot 2026-03-04 at 23 20 01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment