Arrays
Data Structures
Coding
Algorithms
Programming

Finding common elements in two arrays of different size

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

When two arrays have different sizes, the fastest intersection strategy usually takes advantage of the smaller one. The goal is to reduce unnecessary comparisons while still handling duplicates and output rules correctly. In practice, a hash set built from the smaller array is often the best default solution.

Use a Set Built from the Smaller Array

If order does not matter and you want efficient lookup, convert the smaller array into a set and scan the larger array.

python
1def common_elements(a, b):
2    if len(a) > len(b):
3        a, b = b, a
4
5    lookup = set(a)
6    return [x for x in b if x in lookup]
7
8print(common_elements([1, 3, 4, 9], [3, 5, 9, 10, 11]))

This gives average linear time overall, because set membership is typically constant time.

Decide How to Handle Duplicates

The word "common" can mean different things:

  1. unique shared values only
  2. shared values preserving duplicates
  3. shared values in the order of one array

If you want unique results only, wrap the output in a set or track seen results separately.

python
1def unique_common(a, b):
2    if len(a) > len(b):
3        a, b = b, a
4
5    lookup = set(a)
6    seen = set()
7    result = []
8
9    for x in b:
10        if x in lookup and x not in seen:
11            seen.add(x)
12            result.append(x)
13
14    return result

Being explicit about the duplicate rule matters more than micro-optimizing too early.

Use Sorting and Two Pointers When Order or Memory Constraints Matter

If you can sort both arrays and want low additional memory usage, the two-pointer technique is a good alternative.

python
1def common_sorted(a, b):
2    a = sorted(a)
3    b = sorted(b)
4    i = j = 0
5    result = []
6
7    while i < len(a) and j < len(b):
8        if a[i] == b[j]:
9            result.append(a[i])
10            i += 1
11            j += 1
12        elif a[i] < b[j]:
13            i += 1
14        else:
15            j += 1
16
17    return result

This is especially useful when hashing is undesirable or when the data is already sorted.

If the arrays are already sorted, this method becomes especially attractive because you skip the sorting cost and keep memory overhead very low. In that case, the two-pointer scan is often the best overall choice.

Choose Based on the Real Constraint

In most ordinary application code:

  • set-based lookup is simplest and fastest enough
  • two-pointer scanning is good for sorted data
  • brute force is rarely justified except for tiny inputs

The size difference mainly matters because the smaller array should usually become the lookup structure.

If array values are expensive objects rather than small integers, the hashing cost and equality rules also matter. As with most intersection problems, the container choice is really about the data model and output contract, not only the raw array lengths.

That is why a "faster" solution on paper can still be the wrong solution in code if it returns the wrong duplicate semantics or destroys needed ordering guarantees.

Common Pitfalls

  • Building the hash set from the larger array when the smaller one would use less memory.
  • Forgetting to define whether duplicates should appear once or many times.
  • Using brute force nested loops for large inputs without need.
  • Sorting arrays for a one-off operation when hash lookup would be simpler.
  • Assuming all intersection problems have the same output-order requirements.

Summary

  • For arrays of different sizes, build a set from the smaller array and scan the larger one.
  • Clarify duplicate behavior before choosing the implementation.
  • Use two pointers when the data is sorted or low extra memory matters.
  • Avoid brute force except for very small inputs.
  • The best practical solution usually depends more on output rules than on raw array size alone.

Related reading
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.