Find the Prefix Common Array of Two Arrays

Updated on 28 May, 2025
Find the Prefix Common Array of Two Arrays header image

Problem Statement

In this problem, we have to work with two arrays, A and B, each containing a permutation of integers from 1 to n. Our goal is to construct a new array C such that each element C[i] captures the count of numbers that appear in both A and B up to the index i. This concept is described as the prefix common array for A and B.

The challenge involves efficiently comparing elements up to index i in both permutations and counting common numbers to form each corresponding index in array C. We are essentially tracking the accumulation of commonalities between the two arrays as we progress from the start to the end of the arrays.

Examples

Example 1

Input:

A = [1,3,2,4], B = [3,1,2,4]

Output:

[0,2,3,4]

Explanation:

At i = 0: no number is common, so C[0] = 0.
At i = 1: 1 and 3 are common in A and B, so C[1] = 2.
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4.

Example 2

Input:

A = [2,3,1], B = [3,1,2]

Output:

[0,1,3]

Explanation:

At i = 0: no number is common, so C[0] = 0.
At i = 1: only 3 is common in A and B, so C[1] = 1.
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.

Constraints

  • 1 <= A.length == B.length == n <= 50
  • 1 <= A[i], B[i] <= n
  • It is guaranteed that A and B are both a permutation of n integers.

Approach and Intuition

Given the constraints and the nature of the problem, a direct approach can be practical:

  1. Initialize an empty array C which will store the count of common numbers for each index. Also, set up a Set data structure, seen, to keep track of numbers encountered in B as we iterate.

  2. For each index i from 0 to n-1:

    • Add the number at the current index of B to the seen set. This step continually updates which numbers we've encountered in B up to the current index.
    • Initialize a variable, common_count, to zero. This variable will hold the count of common elements for the current index i.
    • Iterate over array A from index 0 to i.
      • For each number in this slice of A, check if it also exists in seen (indicates the current number has been seen in B up to index i).
      • If a number is found in seen, increment the common_count.
    • After finishing this check for all indices up to i, append common_count to array C.

This approach takes advantage of the fact that by using a set, checking for existence is average-case O(1), making it efficient to determine if elements of A up to index i have appeared in B. We deliberately accept a probably higher complexity for clarity and directness due to manageable constraint limits (n <= 50). This method ensures that we correctly build the prefix common array by leveraging the properties of sets for quick lookups and aggregating counts as we progress through the arrays.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    vector<int> calculateCommonPrefix(vector<int>& array1, vector<int>& array2) {
        int length = array1.size();
        vector<int> result(length), elementCounts(length + 1, 0);
        int countShared = 0;

        for (int i = 0; i < length; ++i) {
            if (++elementCounts[array1[i]] == 2) ++countShared;
            if (++elementCounts[array2[i]] == 2) ++countShared;
            result[i] = countShared;
        }

        return result;
    }
};

The provided C++ code defines a function calculateCommonPrefix within a class named Solution. This function aims to find the common prefix array of two integer arrays based on the following principles:

  • The function takes two vectors array1 and array2 as input.
  • It initializes a vector result to store the cumulative number of common prefix elements between the two arrays up to each index.
  • Another vector elementCounts is used to track the occurrences of each element across both arrays.
  • A variable countShared keeps track of the count of shared elements between the two input vectors at each point.

The key steps in the function are:

  1. Iterate through the elements of the input arrays using a for-loop, simultaneously processing elements from both arrays.
  2. Increment the count of each element in elementCounts as it appears in either array. If after incrementing, an element's count reaches two, this indicates that the element now exists in both array1 and array2.
  3. For every element found in both arrays, increment countShared.
  4. Store the current value of countShared in the result vector at the current index, which represents the total number of shared elements up to that point between the two arrays.

Finally, the vector result is returned, which contains the count of common elements up to each index of the input arrays. This function efficiently computes the number of elements common between any two positions of the two arrays using a single loop and provides a direct count by leveraging the indexing property of vectors.

java
class Solution {

    public int[] computeIntersectionCounts(int[] arr1, int[] arr2) {
        int len = arr1.length;
        int[] resultCounts = new int[len];
        int[] elemCount = new int[len + 1];
        int intersectCount = 0;

        // Processing each element for intersections
        for (int idx = 0; idx < len; ++idx) {
            // Increment element counts for current elements from both arrays
            elemCount[arr1[idx]] += 1;
            if (elemCount[arr1[idx]] == 2) ++intersectCount;

            elemCount[arr2[idx]] += 1;
            if (elemCount[arr2[idx]] == 2) ++intersectCount;

            // Accumulate intersect counts in result array
            resultCounts[idx] = intersectCount;
        }

        // Return the array of intersect counts
        return resultCounts;
    }
}

In the provided Java solution, focus on determining the intersection counts between elements of two arrays at each index. The method computeIntersectionCounts in the Solution class achieves this by:

  1. Initializing len to the length of the first array (arr1).
  2. Setting up resultCounts, an array to store the result, and elemCount to keep track of the occurrences of each element across both arrays.
  3. A loop iterates through each index of the arrays:
    • For each index, the method increments the count of the current elements from both arrays in elemCount.
    • If the count of an element reaches 2 (indicating that element is found in both arrays up to this index), the intersectCount is incremented.
    • The total intersectCount up to the current index is stored in resultCounts.
  4. The method returns resultCounts, which provides the cumulative intersection count at each index.

This solution ensures you can track how many times elements of two arrays have matched up to each index, providing a detailed intersection profile across the arrays.

python
class Solution:
    def computeCommonPrefixes(self, numbersA: List[int], numbersB: List[int]) -> List[int]:
        size = len(numbersA)
        result_arr = [0] * size
        occurrences = [0] * (size + 1)
        common_element_count = 0

        for idx in range(size):
            occurrences[numbersA[idx]] += 1
            if occurrences[numbersA[idx]] == 2:
                common_element_count += 1

            occurrences[numbersB[idx]] += 1
            if occurrences[numbersB[idx]] == 2:
                common_element_count += 1

            result_arr[idx] = common_element_count

        return result_arr

The given Python code defines a method to compute the prefix common array between two integer arrays, numbersA and numbersB. The function returns an array wherein each index captures the count of common elements encountered up to that point in the two input arrays. Here's how the computation process works:

  1. Determine the size of the input arrays, assuming both are of equal length, and initialize result_arr with zero values of that size.
  2. Create an occurrences array, sized one larger than the input arrays, initialized with zeros to keep track of the occurrence count of numbers from both arrays.
  3. Initialize common_element_count to zero to count the number of common elements.
  4. Traverse through the input arrays:
    • For each number in numbersA, increase its count in occurrences. If the count reaches two, increment common_element_count.
    • Similarly, update counts for numbersB and adjust common_element_count accordingly.
    • Update result_arr at the current index with the value of common_element_count.
  5. Return result_arr, which holds the cumulative count of common elements at each index.

This operation helps in understanding how many common elements are found progressively when moving through both arrays simultaneously.

Comments

No comments yet.