Find Common Elements Between Two Arrays — LeetCode 2956 Python Solution

EasyArrayHash Table
Problem
#2956
Pattern
Hash Map
Reading time
2 min

The problem

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.

Python solution

Python
class Solution:
    def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]:
        s1, s2 = set(nums1), set(nums2)
        return [sum(x in s2 for x in nums1), sum(x in s1 for x in nums2)]

Complexity

MeasureComplexity
TimeO(n + m)
SpaceO(n + m) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2956. Find Common Elements Between Two Arrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2956. Find Common Elements Between Two Arrays?
LeetCode 2956. Find Common Elements Between Two Arrays is rated Easy on LeetCode.
What is the time complexity of LeetCode 2956. Find Common Elements Between Two Arrays?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 2956. Find Common Elements Between Two Arrays?
The Python solution on this page uses O(n + m) auxiliary space.
What topics does LeetCode 2956. Find Common Elements Between Two Arrays cover?
LeetCode 2956. Find Common Elements Between Two Arrays is tagged Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview