Skip to content
Veltoryx Technologies
FreeProblem 18● EasyLeetCode #349 ↗3 min readUpdated 30 October 2026

Intersection of Two Arrays

Find the unique values two arrays share by sorting both and walking them together with one pointer each.

01The problem

Return the unique values that appear in both arrays. Each value appears once in the result, no matter how many times it repeats. Any order is fine.

nums1nums2Output
[1, 2, 2, 1][2, 2][2]
[4, 9, 5][9, 4, 9, 8, 4][4, 9]

Constraints: 1 to 1000 values each, values 0 to 1000.

02How to spot it

  • Values in both arrays: an intersection.
  • Each value once.
  • Sorting both lets you walk them together, like merging.

03Pseudocode

text
sort a ; sort b
i = 0 ; j = 0
while i < len(a) and j < len(b):
  if a[i] < b[j]: i += 1
  elif a[i] > b[j]: j += 1
  else: add a[i] if not just added
    i += 1 ; j += 1
  1. Sort both arrays.
  2. Move the pointer at the smaller value.
  3. Equal? Record it once, move both.

04Watch it work

Visualizer · step through the algorithmnums1 = [4,9,5], nums2 = [9,4,9,8,4]

a (sorted)

40
51
92
i

b (sorted)

40
41
82
93
94
j

out

Sort both arrays. Now equal values line up, and we can walk both with one pointer each.

Pseudocode

  1. sort a ; sort b
  2. i = 0 ; j = 0
  3. while i < len(a) and j < len(b):
  4. if a[i] < b[j]: i += 1
  5. elif a[i] > b[j]: j += 1
  6. else: add a[i] if not just added
  7. i += 1 ; j += 1

Variables

i
0
j
0
step 1 / 7

05Step-by-step dry run

  1. 1

    a (sorted)

    40
    51
    92
    i

    b (sorted)

    40
    41
    82
    93
    94
    j

    out

    Sort both arrays. Now equal values line up, and we can walk both with one pointer each.

    i = 0j = 0

  2. 2

    a (sorted)

    40
    51
    92
    i

    b (sorted)

    40
    41
    82
    93
    94
    j

    out

    40

    4 = 4: a common value. Record 4 and move both.

    i = 0j = 0out = [4]

  3. 3

    a (sorted)

    40
    51
    92
    i

    b (sorted)

    40
    41
    82
    93
    94
    j

    out

    40

    5 > 4: move j to find a bigger value in b.

    i = 1j = 1

  4. 4

    a (sorted)

    40
    51
    92
    i

    b (sorted)

    40
    41
    82
    93
    94
    j

    out

    40

    5 < 8: 5 can't match anything further in b (only bigger values). Move i.

    i = 1j = 2

  5. 5

    a (sorted)

    40
    51
    92
    i

    b (sorted)

    40
    41
    82
    93
    94
    j

    out

    40

    9 > 8: move j to find a bigger value in b.

    i = 2j = 2

  6. 6

    a (sorted)

    40
    51
    92
    i

    b (sorted)

    40
    41
    82
    93
    94
    j

    out

    40
    91

    9 = 9: a common value. Record 9 and move both.

    i = 2j = 3out = [4, 9]

  7. 7

    a (sorted)

    40
    51
    92

    b (sorted)

    40
    41
    82
    93
    94
    j

    out

    40
    91

    One array has run out, so nothing else can match. The answer is [4, 9].

    out = [4, 9]

06Java solution

IntersectionUnique.java
import java.util.*;

public class IntersectionUnique {
    static int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        List<Integer> out = new ArrayList<>();
        int i = 0, j = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] < nums2[j]) i++;
            else if (nums1[i] > nums2[j]) j++;
            else {
                int v = nums1[i];
                boolean isNew = out.isEmpty() || out.get(out.size() - 1) != v;
                if (isNew) out.add(v); // skip repeated matches
                i++;
                j++;
            }
        }
        int[] res = new int[out.size()];
        for (int k = 0; k < res.length; k++) res[k] = out.get(k);
        return res;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(intersection(new int[] {4, 9, 5}, new int[] {9, 4, 9, 8, 4})));
        System.out.println(Arrays.toString(intersection(new int[] {1, 2, 2, 1}, new int[] {2, 2})));
        System.out.println(Arrays.toString(intersection(new int[] {0, 5, 3}, new int[] {3, 0, 0})));
    }
}
Expected output
[4, 9]
[2]
[0, 3]

Tricky lines, decoded

  • out.get(out.size() - 1) != v: sorted order puts duplicates of a match back to back, so checking the last added value is enough. v is an int, so this compares numbers, not objects.
  • Arrays.sort is O(n log n). Without sorting, use a HashSet instead.

07Why it works

After sorting, the smaller of a[i] and b[j] can't match anything further along in the other array, which only holds bigger values, so skipping it is safe. Equal values are common, and because duplicates are adjacent, comparing with the last recorded value keeps each one unique.

Invariant: every common value smaller than min(a[i], b[j]) is already in out, exactly once.

08Time and space

  • Time: O(n log n + m log m). Sorting dominates; the walk is O(n + m).
  • Space: O(1) not counting the output and the sort's own memory.

09Edge cases

InputOutputWhy it matters
[1] and [2][]nothing in common
[1, 1, 1] and [1][1]unique output
[0, 5, 3] and [3, 0, 0][0, 3]zero is a value
[7, 8] and [9, 10][]disjoint ranges
[1, 2, 2, 1] and [2, 2][2]duplicates collapse

10Common mistakes

  • Adding every match. Returns [2, 2] instead of [2]: skip a value equal to the last one added.
  • Forgetting to sort. The walk only works on sorted input.
  • Comparing Integer objects with !=. Object comparison fails above 127: unbox to int v first.

11Other approaches

ApproachTimeSpaceUse when
Two HashSetsO(n + m)O(n + m)Fastest when memory is fine
Sort + two pointersO(n log n)O(1)Memory matters, or already sorted
Sort one + binary searchO(m log n)O(1)One array is tiny
Streams retainAllO(n + m)O(n)Production code

12In the interview

  • Keep duplicates? That's problem 9, Intersection of Two Arrays II: count instead of dedupe.
  • k arrays? Intersect pairwise, smallest first, or count values across k sets.

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. a[i] = 5 and b[j] = 8. What moves?

  2. 2. Why is checking only the last added value enough to avoid duplicates?

14Solve it yourself

Try it on LeetCode #349.