Intersection of Two Arrays solution explained

To find the values two arrays have in common, each listed once, put the shorter array into a hash set and walk the longer one, keeping any value found in the set and removing it from the set so it is not reported twice. That takes O(n + m) expected time and O(min(n, m)) extra space. If memory is tight or the arrays are already sorted, sort both and merge them with two pointers instead.

By Published 7 min read

The problem, in plain terms

You get two arrays of integers, neither necessarily sorted, and both may contain repeats. Return every value that occurs at least once in each array. Each such value appears in the answer exactly once, and the order of the answer does not matter.

a = [4, 7, 7, 2, 9]
b = [7, 1, 9, 9, 3, 7]

shared values: 7 and 9
answer: [7, 9]   (or [9, 7]; order is free)

with repeats kept (the follow-up):
7 appears twice in a and twice in b -> keep two 7s
9 appears once in a and twice in b  -> keep one 9
answer: [7, 9, 7]   (any order)
A worked example, made up for this page

Ask about sizes before choosing an approach: whether one array is much larger than the other, whether either is already sorted, whether the inputs fit in memory, and whether the result must be sorted. Each answer points to a different best solution, which is exactly why interviewers like this question.

Why a simple problem gets asked

The core solution is a few lines, so the interview value is in the conversation around it. Interviewers use it to see whether you can compare two or three approaches by time, memory and input shape, and whether you can adapt when the constraints change: sorted input, one huge array, data on disk, or counts that matter. Treat it as a trade-off question with a small coding part.

The slowest version: nested loops

For every value in the first array, scan the second array to see whether it appears, and check the result list so you do not add the same value twice. That is O(n × m) for the scans, plus the duplicate checks, and it needs no extra structures beyond the result. It is acceptable for tiny inputs, and stating its cost before improving on it is a good habit.

Approach one: a hash set

Make a set from the shorter array. Walk the longer array; whenever a value is in the set, add it to the answer and remove it from the set. Removing it is what guarantees each shared value is reported once, without a second set for the results. Lookups and removals are O(1) on average, so the whole thing is linear in expectation.

def intersection(a, b):
    if len(a) > len(b):
        a, b = b, a                # build the set from the shorter list
    pending = set(a)
    out = []
    for x in b:
        if x in pending:
            out.append(x)
            pending.remove(x)      # report each shared value once
    return out
Python: set from the shorter list, remove on first hit so each value is reported once.

In Python, list(set(a) & set(b)) gives the same values in one line and is a perfectly good thing to say first. The explicit loop is worth knowing because it carries over to languages without a built-in set intersection and to the follow-up below.

Approach two: sort both, then merge

Sort both arrays and walk them with one index each. If the current values differ, advance the index pointing at the smaller one. If they are equal, record the value (unless it equals the last value recorded) and advance both. This uses no hash table and only O(1) extra memory beyond the sort, and if the inputs arrive sorted it is linear with no hashing at all. The output comes out sorted, which is sometimes a requirement.

#include <algorithm>
#include <vector>

std::vector<int> intersection(std::vector<int> a, std::vector<int> b) {
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());
    std::vector<int> out;
    std::size_t i = 0, j = 0;
    while (i < a.size() && j < b.size()) {
        if (a[i] < b[j]) {
            ++i;
        } else if (a[i] > b[j]) {
            ++j;
        } else {
            if (out.empty() || out.back() != a[i]) out.push_back(a[i]);
            ++i;
            ++j;
        }
    }
    return out;
}
C++17: takes copies, sorts them, and merges. The output is sorted and has no repeats.

Passing the vectors by value makes the function sort its own copies, so the caller's data is left alone. If changing the inputs is acceptable, take them by reference and skip the copies.

Complexity summary

n and m are the array lengths, with m the smaller
ApproachTimeExtra space
Nested loopsO(n × m)O(1) besides the output
Hash set of the smaller arrayO(n + m) expectedO(m)
Sort both, two-pointer mergeO(n log n + m log m)O(1) to O(n + m), depending on the sort and copies
Already sorted, two-pointer mergeO(n + m)O(1)
Sort the smaller, binary search from the largerO((n + m) log m)O(1) besides the sort
n and m are the array lengths, with m the smaller. Scroll sideways on a small screen.

The last row matters when one array is tiny and the other is enormous: sorting only the small one and binary searching it for each value of the big one avoids building a large set. If the big array lives on disk and cannot fit in memory, stream it past an in-memory set of the small one.

The follow-up: keep repeats

When a value should appear as many times as it occurs in both arrays, replace the set with a count map. Count the shorter array, walk the longer one, and each time a value still has a positive count, output it and decrement the count.

from collections import Counter


def intersect_with_counts(a, b):
    if len(a) > len(b):
        a, b = b, a
    left = Counter(a)
    out = []
    for x in b:
        if left[x] > 0:
            out.append(x)
            left[x] -= 1
    return out
Python: intersection with multiplicity, using collections.Counter.

Reading left[x] for a missing key returns 0 and does not add the key, which is why the check works without a membership test first.

Edge cases to test

  • Either array empty, which gives an empty answer.
  • No shared values at all.
  • Identical arrays with many repeats, which should still list each value once.
  • Negative numbers and zero.
  • One array much longer than the other, to check the swap so the set is built from the smaller one.

Pitfalls

  • Reporting a value once per occurrence in the longer array, which happens if you forget to remove it from the set.
  • Building the set from the larger array, which works but uses more memory than needed.
  • In the merge version, forgetting to move the indexes after a match, which loops forever on the same pair.
  • Assuming the answer must be sorted. Ask; if it must, the merge version gives that for free.
  • Using the multiplicity version when the question asked for distinct values, or the reverse.

How to explain it out loud

Fictional example

Laying out the options before coding
Candidate
The simplest fast answer is a set from the smaller array and one pass over the bigger one. When I find a match, I add it and remove it from the set so it's only reported once. That's linear time and memory proportional to the smaller array.
Candidate
If the arrays were already sorted, or memory were tight, I'd sort and walk both with two pointers. That needs no hash table and gives sorted output.
Candidate
And if one array were tiny compared to the other, I'd sort just the tiny one and binary search it. Which of these fits depends on the sizes, so can I ask what they look like?

Counting values with a map is also how Find All Anagrams in a String compares a moving window with a pattern. The two-pointer walk over sorted arrays is the same motion used in Merge Sorted Array, where equal values are kept instead of matched.

Rehearsing it with Natively

Since this question is mostly about choosing between approaches, the useful practice is saying the trade-offs clearly. During a practice session on Mac or Windows, Natively can read the prompt from a screenshot, suggest the follow-up questions an interviewer may ask, and help you check your C++ or Python against tricky inputs. Its transcript shows afterward whether you asked about input sizes before you started coding. See AI tools for coding interview preparation.

Questions people ask

How do you find the intersection of two arrays?

Put the shorter array into a hash set, then scan the longer array. Each value found in the set goes into the answer and is removed from the set, so every shared value appears once.

What is the time complexity of Intersection of Two Arrays?

O(n + m) expected time with a hash set, using memory proportional to the smaller array. Sorting both and merging with two pointers takes O(n log n + m log m) and needs no hash table.

When is the sort-and-merge approach better?

When the arrays are already sorted, when memory is tight, or when the output must be sorted. On sorted input the merge is linear with constant extra space.

How do you keep repeated values in the intersection?

Replace the set with a count map of the shorter array. Walk the longer array and output a value each time its remaining count is positive, then decrement that count.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP