2657. Find the Prefix Common Array of Two Arrays

Explanation:

To find the prefix common array of two arrays A and B, we iterate through both arrays simultaneously and count the numbers that are common up to the current index. We keep track of the count in a separate array C.

  1. Initialize an array C of size n with all elements as 0.
  2. Iterate through arrays A and B simultaneously.
  3. For each index i, count the common elements up to index i in arrays A and B.
  4. Update the count in array C at index i.
  5. Return the array C as the prefix common array.

Time complexity: O(n) where n is the length of the input arrays A and B. Space complexity: O(n) for the output array C.

class Solution {
    public int[] prefixCommonArray(int[] A, int[] B) {
        int n = A.length;
        int[] C = new int[n];
        
        for (int i = 0; i < n; i++) {
            int count = 0;
            for (int j = 0; j <= i; j++) {
                if (contains(A, B, A[j])) {
                    count++;
                }
            }
            C[i] = count;
        }
        
        return C;
    }
    
    private boolean contains(int[] A, int[] B, int num) {
        for (int i = 0; i < A.length; i++) {
            if (A[i] == num && B[i] == num) {
                return true;
            }
        }
        return false;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.