Return the distinct values that appear in both arrays.
Given two integer arrays, return an array containing the values that appear in both arrays. Each value should appear at most once in the result, and the order of the returned values does not matter.
A common approach is to use a hash-based structure to record which values have been seen, then collect the overlap while avoiding duplicates.
Input Format
- Two integer arrays,
nums1andnums2. - Each array may contain duplicate values.
Treat the arrays as the two inputs to the function; no special file or stream format is required.
Output Format
- Return an array of the distinct integers present in both inputs.
- The order of elements in the output may be arbitrary.
Constraints
- 0 <= nums1.length, nums2.length
- Values may repeat within an array.
- The result must contain no duplicates.
- If there is no common value, return an empty array.
Example 1
Input
nums1 = [1,2,2,1], nums2 = [2,2]
Output
[2]
Explanation
The only value present in both arrays is 2.
Example 2
Input
nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output
[9,4]
Explanation
Both 4 and 9 appear in the two arrays. The order does not matter, so [4,9] is also valid.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.