Skip to main content
Back to problems
#350
Easy Algorithms

Intersection of two arrays ii

Array Hash Table Two Pointers Binary Search Sorting
59.7% acceptance
Jan 12, 2026
8171
1010
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
    use std::collections::HashMap;
    let mut count = HashMap::new();
    for num in nums1 {
      *count.entry(num).or_insert(0) += 1;
    }
    
    let mut result = Vec::new();
    for num in nums2 {
      if let Some(c) = count.get_mut(&num) {
        if *c > 0 {
          result.push(num);
          *c -= 1;
        }
      }
    }
    
    result
  }
}