← PayPal bank

PayPal · Question 12 · Arrays

Intersection of Two Arrays II

ArraysJavacode⏱ O(n+m)💾 O(min(n,m))
Product-based

Problem

Return the intersection of two arrays including duplicates.

Approach

Use a HashMap to count frequencies.

Time O(n+m)Space O(min(n,m))

How it works

  1. 1Count nums1 frequencies.
  2. 2Spend counts matching nums2 in order.

Sample input / output

Input:
nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Output:
[2, 2]

Constraints

1 <= lengths <= 1000; result in any order.

Solution — read it, then walk it

Time O(n+m)Space O(min(n,m))Loops 3Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]intersect(int[] nums1,int[] nums2)Map<Integer, Integer> map =new HashMap<>()for (int num : nums1)map.put(num,map.getOrDefault(num, 0) +1)List<Integer> result = newArrayList<>()for (int num : nums2)if(map.getOrDefault(num,0) > 0)result.add(num)map.put(num, map.get(num) -1)DEFINE [] res = newint[result.size()]for (int i = 0; i <result.size(); i++)res[i] = result.get(i)RETURN resDEFINE static voidmain(String[] args)System.out.println(Arrays.toString(intersect(newint[]{1, 2, 2, 1}, newint[]{2, 2})))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/18

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits