Leetcode 2956: Find Common Elements Between Two Arrays

grid47
grid47
Exploring patterns and algorithms
Jan 16, 2024 5 min read

You are given two integer arrays, nums1 and nums2, with sizes n and m respectively. Your task is to find the number of indices i such that nums1[i] exists in nums2 and the number of indices i such that nums2[i] exists in nums1. Return both values as an array [answer1, answer2].
Problem
Approach
Steps
Complexity
Input: Two integer arrays nums1 and nums2.
Example: nums1 = [2, 3, 2], nums2 = [1, 2]
Constraints:
• 1 <= n, m <= 100
• 1 <= nums1[i], nums2[i] <= 100
Output: Return an array of two integers: [answer1, answer2]. answer1 is the number of elements from nums1 that are present in nums2, and answer2 is the number of elements from nums2 that are present in nums1.
Example: [2, 1]
Constraints:
Goal: To find the count of matching elements between the two arrays in both directions.
Steps:
• Convert nums1 and nums2 into sets for efficient lookup.
• Iterate through nums1 and count how many of its elements exist in nums2.
• Similarly, iterate through nums2 and count how many of its elements exist in nums1.
Goal: The arrays have a maximum size of 100 elements, and each element is between 1 and 100.
Steps:
• n == nums1.length
• m == nums2.length
• 1 <= nums1[i], nums2[i] <= 100
Assumptions:
• Both input arrays will have at least one element.
Input: Input: nums1 = [2, 3, 2], nums2 = [1, 2]
Explanation: The elements in nums1 that exist in nums2 are 2 and 2, so answer1 is 2. The element 2 in nums2 exists in nums1, so answer2 is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus