Find the Prefix Common Array of Two Arrays - Problem

You are given two 0-indexed integer permutations A and B of length n.

A prefix common array of A and B is an array C such that C[i] is equal to the count of numbers that are present at or before the index i in both A and B.

Return the prefix common array of A and B.

A sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.

Input & Output

Example 1 — Basic Case
$ Input: A = [1,3,2,4], B = [3,1,2,4]
Output: [0,2,3,4]
💡 Note: At index 0: A[0]=1, B[0]=3, no common elements → 0. At index 1: A[0:1]=[1,3], B[0:1]=[3,1], common=[1,3] → 2. At index 2: A[0:2]=[1,3,2], B[0:2]=[3,1,2], common=[1,2,3] → 3. At index 3: A[0:3]=[1,3,2,4], B[0:3]=[3,1,2,4], common=[1,2,3,4] → 4.
Example 2 — Same Elements Different Order
$ Input: A = [2,3,1], B = [3,1,2]
Output: [0,0,3]
💡 Note: At index 0: A[0]=2, B[0]=3, no common → 0. At index 1: A[0:1]=[2,3], B[0:1]=[3,1], common=[3] but we need both → 0 (only 3 is common). At index 2: A[0:2]=[2,3,1], B[0:2]=[3,1,2], all elements are now common → 3.
Example 3 — Minimum Size
$ Input: A = [1,2], B = [2,1]
Output: [0,2]
💡 Note: At index 0: A[0]=1, B[0]=2, no common elements → 0. At index 1: A[0:1]=[1,2], B[0:1]=[2,1], both elements are common → 2.

Constraints

  • 1 ≤ A.length == B.length ≤ 1000
  • 1 ≤ A[i], B[i] ≤ A.length
  • A and B are permutations of integers from 1 to A.length

Visualization

Tap to expand
Find the Prefix Common Array of Two ArraysInput:1324A =3124B =Count common elements in each prefixOutput:0234C =Index 0: {1} ∩ {3} = {} → 0Index 1: {1,3} ∩ {3,1} = {1,3} → 2Index 2: {1,3,2} ∩ {3,1,2} = {1,2,3} → 3Index 3: {1,3,2,4} ∩ {3,1,2,4} = {1,2,3,4} → 4
Understanding the Visualization
1
Input Arrays
Two permutation arrays A and B of same length
2
Process Prefixes
At each index, count common elements in prefixes A[0:i] and B[0:i]
3
Result Array
Array C where C[i] = count of common elements up to index i
Key Takeaway
🎯 Key Insight: Use a frequency counter to detect when elements appear in both array prefixes - when frequency reaches 2, the element becomes common.
Asked in
Google 15 Microsoft 12 Amazon 8
29.8K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen