Skip to main content
Back to problems
#2956
Easy Algorithms

Find common elements between two arrays

Array Hash Table
84.4% acceptance
Feb 25, 2026
301
109
You are given two integer arrays nums1 and nums2 of sizes n and m, respectively. Calculate the following values: answer1 : the number of indices i such that nums1[i] exists in nums2. answer2 : the number of indices i such that nums2[i] exists in nums1. Return [answer1,answer2].

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_intersection_values(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
    use std::collections::HashSet;
    let set1: HashSet<i32> = nums1.iter().cloned().collect();
    let set2: HashSet<i32> = nums2.iter().cloned().collect();
    let a1 = nums1.iter().filter(|x| set2.contains(x)).count() as i32;
    let a2 = nums2.iter().filter(|x| set1.contains(x)).count() as i32;
    vec![a1, a2]
  }
}