[LeetCode] Find the Prefix Common Array of Two Arrays

2657. Find the Prefix Common Array of Two Arrays

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
unordered_map<int, int> freq;
vector<int> res;
int now = 0;
for(int i = 0; i < A.size(); i++) {
if(++freq[A[i]] == 0) now += 1;
if(--freq[B[i]] == 0) now += 1;
res.push_back(now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/30/PS/LeetCode/find-the-prefix-common-array-of-two-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.