1213. Intersection of Three Sorted Arrays

Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.

 

Example 1:

Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
Output: [1,5]
Explanation: Only 1 and 5 appeared in the three arrays.

Example 2:

Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]
Output: []

 

Constraints:

  • 1 <= arr1.length, arr2.length, arr3.length <= 1000
  • 1 <= arr1[i], arr2[i], arr3[i] <= 2000

Rust Solution

struct Solution;

use std::collections::BTreeMap;

impl Solution {
    fn arrays_intersection(arr1: Vec<i32>, arr2: Vec<i32>, arr3: Vec<i32>) -> Vec<i32> {
        let mut btm: BTreeMap<i32, i32> = BTreeMap::new();
        for x in arr1 {
            *btm.entry(x).or_default() += 1;
        }
        for x in arr2 {
            *btm.entry(x).or_default() += 1;
        }
        for x in arr3 {
            *btm.entry(x).or_default() += 1;
        }
        let mut res = vec![];
        for (k, v) in btm {
            if v == 3 {
                res.push(k);
            }
        }
        res
    }
}

#[test]
fn test() {
    let arr1 = vec![1, 2, 3, 4, 5];
    let arr2 = vec![1, 2, 5, 7, 9];
    let arr3 = vec![1, 3, 4, 5, 8];
    let res = vec![1, 5];
    assert_eq!(Solution::arrays_intersection(arr1, arr2, arr3), res);
}

Having problems with this solution? Click here to submit an issue on github.