Problem Description
Given two integer arrays nums1 and nums2, count how many indices i in nums1 such that nums1[i] exists in nums2, and count how many indices i in nums2 such that nums2[i] exists in nums1. Return the results as an array [answer1, answer2].
Key Insights
- Use sets to store elements from each array for O(1) membership checks.
- Iterate through each array and count indices where the element exists in the opposite set.
- The problem is straightforward with small input sizes (up to 100 elements).
Space and Time Complexity
Time Complexity: O(n + m), where n = nums1.length and m = nums2.length
Space Complexity: O(n + m), for storing the elements in sets for both arrays
Solution
The solution uses hash sets to store unique numbers from each of the arrays. For each element in nums1, we check if it exists in the set for nums2 and vice versa. This provides constant time lookups for each membership test, ensuring the overall time complexity remains O(n + m). The main trick is leveraging the properties of sets to avoid nested loops and redundant comparisons.