Skip to content

2657. Find the Prefix Common Array of Two Arrays 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
    const int n = A.size();
    int prefixCommon = 0;
    vector<int> ans;
    vector<int> count(n + 1);

    for (int i = 0; i < A.size(); ++i) {
      if (++count[A[i]] == 2)
        ++prefixCommon;
      if (++count[B[i]] == 2)
        ++prefixCommon;
      ans.push_back(prefixCommon);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] findThePrefixCommonArray(int[] A, int[] B) {
    final int n = A.length;
    int prefixCommon = 0;
    int[] ans = new int[n];
    int[] count = new int[n + 1];

    for (int i = 0; i < A.length; ++i) {
      if (++count[A[i]] == 2)
        ++prefixCommon;
      if (++count[B[i]] == 2)
        ++prefixCommon;
      ans[i] = prefixCommon;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def findThePrefixCommonArray(self, A: list[int], B: list[int]) -> list[int]:
    n = len(A)
    prefixCommon = 0
    ans = []
    count = [0] * (n + 1)

    for a, b in zip(A, B):
      count[a] += 1
      if count[a] == 2:
        prefixCommon += 1
      count[b] += 1
      if count[b] == 2:
        prefixCommon += 1
      ans.append(prefixCommon)

    return ans