Find the Prefix Common Array of Two Arrays

You are given two permutations A and B of the integers 1 to n. The prefix common array C has C[i] equal to the number of values that appear in both A[0..i] and B[0..i]. Return C.

30:00

Find the Prefix Common Array of Two Arrays
medium
Free written solution
Topics
Companies

You are given two permutations A and B of the integers 1 to n. The prefix common array C has C[i] equal to the number of values that appear in both A[0..i] and B[0..i]. Return C.

Example 1:
Input: {"A":[1,3,2,4],"B":[3,1,2,4]}
Output: [0,2,3,4]
Constraints:
  • 1≤A.length==B.length==n≤501 \leq A.\text{length} == B.\text{length} == n \leq 50

  • 1≤A[i],B[i]≤n1 \leq A[i], B[i] \leq n

  • A and B are both permutations of the integers 1 to n.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"A":[1,3,2,4],"B":[3,1,2,4]}

Keep a counter per value 1..4. A value is common once both prefixes contain it, which is exactly when its counter reaches 2.

prefixes read so far

A

1

0

3

1

2

2

4

3

B

3

0

1

1

2

2

4

3

seen[v]: one half per array

common = 0

1

0

2

0

3

0

4

0

blue half = in A prefix

amber half = in B prefix

green = count 2, common

C (prefix common array)

·
·
·
·
Variables
VariableValue
n4
common0
DepthFunction Call
Stack empty
0/13