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
Prefix Common Array - Single Pass Approach INPUT Array A: 1 3 2 4 i=0 i=1 i=2 i=3 Array B: 3 1 2 4 Permutation: contains integers 1 to n exactly once n = 4 Track with freq[]: 0 0 0 0 0 [0] [1] [2] [3] [4] ALGORITHM STEPS 1 Initialize freq[n+1]=0, common=0 2 For each index i Process A[i] and B[i] 3 Increment freq freq[A[i]]++, freq[B[i]]++ 4 Check freq == 2 If freq reaches 2, increment common count Iteration Trace: i A[i] B[i] new=2 C[i] 0 1 3 0 0 1 3 1 +2 2 2 2 2 +1 3 3 4 4 +1 4 FINAL RESULT Output Array C: 0 2 3 4 C[0] C[1] C[2] C[3] Meaning: C[0]=0: No common yet (A has 1, B has 3) C[1]=2: Both have {1,3} in first 2 positions C[2]=3: Both have {1,2,3} in first 3 positions C[3]=4: All {1,2,3,4} are common (complete) OK Key Insight: Use a frequency array where freq[x] tracks how many times number x has appeared across both arrays. When freq[x] becomes 2, that number is now present in both A and B's prefixes. This single-pass approach achieves O(n) time complexity by avoiding repeated counting at each index. TutorialsPoint - Find the Prefix Common Array of Two Arrays | Optimized Single Pass Approach
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