Find the Prefix Common Array of Two Arrays - Problem

Imagine you're comparing two playlists of your favorite songs, where each playlist contains the same n songs but in different orders. You want to track how many songs appear in both playlists as you go through them position by position.

You are given two 0-indexed integer permutations A and B of length n. Think of these as two different arrangements of numbers from 1 to n, where each number appears exactly once in each array.

Your task is to create a prefix common array C where C[i] represents the count of numbers that have appeared at or before index i in both arrays A and B.

Example: If A = [1,3,2,4] and B = [3,1,2,4], then:

  • At index 0: We've seen {1} in A and {3} in B → 0 common elements
  • At index 1: We've seen {1,3} in A and {3,1} in B → 2 common elements
  • At index 2: We've seen {1,3,2} in A and {3,1,2} in B → 3 common elements
  • At index 3: We've seen {1,3,2,4} in A and {3,1,2,4} in B → 4 common elements

So the result would be [0,2,3,4].

Input & Output

example_1.py — Basic Case
$ Input: A = [1,3,2,4], B = [3,1,2,4]
Output: [0,2,3,4]
💡 Note: At index 0: A has {1}, B has {3} → 0 common. At index 1: A has {1,3}, B has {3,1} → 2 common. At index 2: A has {1,3,2}, B has {3,1,2} → 3 common. At index 3: A has {1,3,2,4}, B has {3,1,2,4} → 4 common.
example_2.py — Identical Arrays
$ Input: A = [2,3,1], B = [2,3,1]
Output: [1,2,3]
💡 Note: Since both arrays are identical, at each position i we have i+1 common elements: [1,2,3].
example_3.py — Reverse Order
$ Input: A = [1,2,3], B = [3,2,1]
Output: [0,1,3]
💡 Note: At index 0: {1} vs {3} → 0 common. At index 1: {1,2} vs {3,2} → 1 common (element 2). At index 2: {1,2,3} vs {3,2,1} → 3 common (all elements).

Constraints

  • 1 ≤ A.length == B.length ≤ 50
  • 1 ≤ A[i], B[i] ≤ A.length
  • A and B are permutations of integers from 1 to n
  • Each integer from 1 to n appears exactly once in each array

Visualization

Tap to expand
Race Track VisualizationTrack A: [1, 3, 2, 4]1324Track B: [3, 1, 2, 4]3124Checkpoint 1Common: 0Checkpoint 2Common: 2ScoreboardRacer 1: ✓ ✓Racer 3: ✓ ✓Racer 2: ⋯
Understanding the Visualization
1
Setup Scoreboard
Create a scoreboard to track which racers have been seen on each track
2
Process Checkpoints
At each checkpoint, mark racers as seen and count those appearing on both tracks
3
Running Total
Maintain a running count of racers common to both tracks at each checkpoint
Key Takeaway
🎯 Key Insight: Since each number appears exactly once in each array, we only need to count frequency up to 2 - when an element reaches frequency 2, it means it has appeared in both arrays.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K 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