Skip to content

Commit 0416953

Browse files
authored
Create 2657-find-the-prefix-common-array-of-two-arrays.cpp
1 parent 198f27b commit 0416953

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
You are given two 0-indexed integer permutations A and B of length n.
3+
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.
4+
Return the prefix common array of A and B.
5+
A sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
6+
7+
Ex. Input: A = [1,3,2,4], B = [3,1,2,4]
8+
Output: [0,2,3,4]
9+
Explanation: At i = 0: no number is common, so C[0] = 0.
10+
At i = 1: 1 and 3 are common in A and B, so C[1] = 2.
11+
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
12+
At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4.
13+
14+
Time : O(n)
15+
Space : O(n)
16+
*/
17+
18+
class Solution {
19+
public:
20+
vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
21+
vector<int> C;
22+
vector<int> v(A.size()+1,0);
23+
int count = 0;
24+
25+
for(int i = 0; i < A.size(); ++i){
26+
if(v[A[i]] < 0)
27+
count++;
28+
++v[A[i]];
29+
30+
if(v[B[i]]>0)
31+
count++;
32+
--v[B[i]];
33+
34+
C.push_back(count);
35+
}
36+
return C;
37+
}
38+
};

0 commit comments

Comments
 (0)