Menu
CoddyTech

Intersection of Two Arrays

EasyHashingpython iconjava iconcpp iconc iconjs icon+10

You get two arrays of integers, nums1 and nums2. Return every value that appears in both arrays, sorted in increasing order. Each shared value appears in the answer once, however many times it repeats in either array.

Function

intersection(nums1: integer-array, nums2: integer-array) → integer-array
nums1integer-array
the first list of integers
nums2integer-array
the second list of integers
Returnsinteger-array
the values found in both lists, each once, in increasing order

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 5000
  • -105 ≤ nums1[i], nums2[i] ≤ 105
  • At least one value appears in both arrays.

Examples

Input
nums1 = [6, 2, 9, 2, 4]nums2 = [4, 4, 1, 6]
Output
[4, 6]
Explanation
4 and 6 are in both arrays. 4 appears twice in nums2 but is listed once, and 2 and 9 never appear in nums2.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

What if nums1 holds 10 values and nums2 holds a million, already sorted? Which approach would you pick, and can binary search beat a full walk?

Reset code
def intersection(nums1, nums2):
    # Write code here
Test cases

Case 1

Case 2

Input

nums1 = [6, 2, 9, 2, 4]
nums2 = [4, 4, 1, 6]

Expected

[4, 6]