Java, find intersection of two arrays
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Finding the intersection of two arrays sounds simple until you need to decide what "intersection" actually means. Some use cases want unique values only, while others want duplicates preserved based on frequency. In Java, the right implementation depends on that rule, plus whether you care more about simplicity, order, or time complexity.
Define the Intersection Rule First
Before writing code, choose one of these interpretations:
- Unique intersection: each common value appears once in the result.
- Multiset intersection: duplicates are preserved up to the minimum count in both arrays.
For arrays 1, 2, 2, 3 and 2, 2, 4, the unique intersection is 2, while the multiset intersection is 2, 2.
That distinction changes the data structure you should use.
Unique Intersection With HashSet
If you only need unique values, use a set for fast membership checks. This keeps the code short and runs in linear time on average.
This is the best baseline for most interview-style or data-cleaning cases where duplicates are irrelevant.
Preserving Duplicates With a Frequency Map
If duplicates matter, a set is not enough because it loses counts. Use a frequency map for one array, then consume matches from the other.
This returns 2, 2, which is correct for multiset logic.
Sorting as an Alternative
If the arrays are already sorted, or if sorting cost is acceptable, you can use a two-pointer scan. This avoids hashing and can be memory efficient.
This pattern naturally preserves duplicate matches and is useful when you want deterministic numeric ordering in the output.
Which Approach Should You Choose
Use HashSet when:
- You only care about unique common values.
- Output order does not matter.
- You want the simplest linear solution.
Use a frequency map when:
- Duplicate counts matter.
- You want linear behavior without sorting both arrays.
Use sorting and two pointers when:
- Arrays are already sorted or easy to sort.
- You want to minimize extra map overhead.
- Ordered output is useful.
Common Pitfalls
- Writing an intersection method without defining whether duplicates should be preserved.
- Using
List.containsinside a loop, which turns the solution into quadratic time for large inputs. - Forgetting that
HashSetdoes not preserve insertion order. - Sorting the input arrays in place when callers expect the original order to remain unchanged.
- Returning boxed
Integercollections when the rest of the code expects primitiveint[].
Summary
- Decide first whether you want unique or multiset intersection semantics.
- '
HashSetis the simplest solution for unique results.' - A frequency map is the correct choice when duplicates matter.
- Sorting plus two pointers is a good option for ordered or already sorted data.
- The main bug source is ambiguity in requirements, not Java syntax.
Related reading
- Java implementation of Sieve of Eratosthenes that can go past n 232?
- java indexofString str method complexity
- Java recursive Fibonacci sequence
- Java Sorting an array based on another array with indexOf method
- Java function for arrays like PHP's join()?
- Java Get first item from a collection
- Java Future vs c async await
- Java FutureTask Exception

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.