← Home

349. Intersection of Two Arrays

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
349

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 349. Intersection of Two Arrays, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are intersection.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given two arrays, write a function to compute their intersection.
03
04Example 1:
05
06Input: nums1 = [1,2,2,1], nums2 = [2,2]
07Output: [2]
08Example 2:
09
10Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
11Output: [9,4]
12Note:
13
14Each element in the result must be unique.
15The result can be in any order.
16**/
17
18//Runtime: 16 ms, faster than 14.90% of C++ online submissions for Intersection of Two Arrays.
19//Memory Usage: 8.8 MB, less than 99.41% of C++ online submissions for Intersection of Two Arrays.
20
21/**
22class Solution {
23public:
24    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
25        vector<int> ans;
26        for(int num : nums1){
27            if(find(nums2.begin(), nums2.end(), num)!=nums2.end()){
28                if(find(ans.begin(), ans.end(), num)==ans.end()){
29                    ans.push_back(num);
30                }
31            }
32        }
33        return ans;
34    }
35};
36**/
37
38//Runtime: 12 ms, faster than 58.27% of C++ online submissions for Intersection of Two Arrays.
39//Memory Usage: 9.8 MB, less than 11.28% of C++ online submissions for Intersection of Two Arrays.
40class Solution {
41public:
42    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
43        set<int> s1(nums1.begin(), nums1.end());
44        set<int> s2(nums2.begin(), nums2.end());
45        vector<int> ans(max(nums1.size(), nums2.size()));
46        vector<int>::iterator it = set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), ans.begin());
47        ans.resize(it - ans.begin());
48        return ans;
49    }
50};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.