Find the Prefix Common Array of Two Arrays (LeetCode 2657): Solution and Explanation

Medium
Array
Hash Table
Bit Manipulation

For every index i, count how many values appear in both A[0..i] and B[0..i], where A and B are permutations of 1 to n.

Intuition

Recomputing the intersection of two prefixes at every index costs O(n) per index and O(n^2) overall. The prefixes only grow by one element each step, so most of that work repeats.

Both arrays are permutations, so every value shows up exactly once in A and exactly once in B. A value is in both prefixes precisely when it has been seen twice in total.

So keep a counter per value. Each time a counter climbs to 2, one more value has become common, and it stays common for every later index.

Approach: Count to two

  1. Create seen of size n + 1 filled with 0 and set common = 0.
  2. For each index i, increment seen[A[i]]. If it is now 2, add one to common.
  3. Increment seen[B[i]]. If it is now 2, add one to common. This also handles A[i] == B[i], which reaches 2 on the second increment.
  4. Write common into C[i].
  5. Return C.

Step-by-step example

A = [1,3,2,4], B = [3,1,2,4]
  1. i = 0: seen[1] = 1 from A, seen[3] = 1 from B. Nothing has count 2, so C[0] = 0.
  2. i = 1: A adds 3, whose count becomes 2, so common = 1. B adds 1, whose count becomes 2, so common = 2. C[1] = 2.
  3. i = 2: A adds 2 (count 1), then B adds 2 (count 2), so common = 3. C[2] = 3.
  4. i = 3: the same happens with 4, so common = 4. C[3] = 4.
  5. Return [0,2,3,4].

Code: Python, Java, C++

1class Solution:
2    def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]:
3        n = len(A)
4        seen = [0] * (n + 1)
5        common = 0
6        ans = []
7        for i in range(n):
8            seen[A[i]] += 1
9            if seen[A[i]] == 2:
10                common += 1
11            seen[B[i]] += 1
12            if seen[B[i]] == 2:
13                common += 1
14            ans.append(common)
15        return ans
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the indices with two constant-time counter updates per index.

Space

O(n)

The counter array has n + 1 entries, plus the output array.

Other approaches

Two bitmasks (time O(n), space O(1))

Keep one 64-bit mask per array and set bit v when the value appears. C[i] is the popcount of maskA AND maskB. Works because n is at most 50.

Recount each prefix (time O(n^2), space O(n))

For each i, put A[0..i] in a set and count how many of B[0..i] are in it. Simple, but quadratic.

Common mistakes

  • Checking only whether A[i] is in B's prefix and B[i] is in A's prefix, then forgetting the case A[i] == B[i], which should count once, not twice or zero times.
  • Resetting the count at each index. Once a value is common it stays common, so the total only grows.
  • Sizing the counter array as n instead of n + 1, since the values run from 1 to n.

Frequently asked questions

Why does a count of 2 mean the value is in both prefixes?

Each value appears exactly once in each permutation. Two sightings can only come from one in A and one in B.

Is C always non-decreasing?

Yes. Prefixes only grow, so a common value never stops being common. The last entry is always n.

Why is this filed under bit manipulation?

With n at most 50, the sets of seen values fit in 64-bit masks, and C[i] is the popcount of their AND. The counter array does the same job and is easier to read.