Find Common Elements Between Two Arrays — LeetCode 2956 Python Solution
- Problem
- #2956
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n + m) |
| Space | O(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.