/**
* Problem: LeetCode 2657 - Find the Prefix Common Array of Two Arrays
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int[] findThePrefixCommonArray(int[] A, int[] B) {
int n = A.length;
int[] C = new int[n];
int[] freq = new int[n + 1];
int commonCount = 0;
for (int i = 0; i < n; i++) {
// Track frequency of A[i]
if (++freq[A[i]] == 2) {
commonCount++;
}
// Track frequency of B[i]
if (++freq[B[i]] == 2) {
commonCount++;
}
C[i] = commonCount;
}
return C;
}
}
"""
Problem: LeetCode 2657 - Find the Prefix Common Array of Two Arrays
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]:
n = len(A)
C = [0] * n
freq = [0] * (n + 1)
common_count = 0
for i in range(n):
freq[A[i]] += 1
if freq[A[i]] == 2:
common_count += 1
freq[B[i]] += 1
if freq[B[i]] == 2:
common_count += 1
C[i] = common_count
return C
/**
* Problem: LeetCode 2657 - Find the Prefix Common Array of Two Arrays
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
int n = A.size();
vector<int> C(n, 0);
vector<int> freq(n + 1, 0);
int commonCount = 0;
for (int i = 0; i < n; ++i) {
if (++freq[A[i]] == 2) {
commonCount++;
}
if (++freq[B[i]] == 2) {
commonCount++;
}
C[i] = commonCount;
}
return C;
}
};
/**
* Problem: LeetCode 2657 - Find the Prefix Common Array of Two Arrays
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[]} A
* @param {number[]} B
* @return {number[]}
*/
var findThePrefixCommonArray = function(A, B) {
const n = A.length;
const C = new Array(n);
const freq = new Uint8Array(n + 1);
let commonCount = 0;
for (let i = 0; i < n; i++) {
if (++freq[A[i]] === 2) {
commonCount++;
}
if (++freq[B[i]] === 2) {
commonCount++;
}
C[i] = commonCount;
}
return C;
};