2657. Find the Prefix Common Array of Two Arrays

  • Array
  • Hash Table
  • Counting
TIME
O(n)
SPACE
O(n)
problem on leetcode ↗source on github ↗

Intuition

At each index, one value from A and one value from B become available in the prefixes.

Because both arrays are permutations of 1 to n, a value becomes common exactly when we have seen it twice in total: once from A and once from B.

Approach

  1. Keep a count array seen of size n + 1.
  2. Keep a running common count.
  3. For each index i:
    • increment seen[A[i]]; if it becomes 2, increment common
    • increment seen[B[i]]; if it becomes 2, increment common
    • store common in the answer
  4. Return the answer array.

Complexity

  • Time: O(n)
  • Space: O(n)

Edge Cases

  • A[i] == B[i] -> the value is counted as common at the same index
  • No common value in early prefixes -> answer contains 0
  • Last index always reaches n because both arrays are permutations
  • Single element arrays -> return [1]

Code

from typing import List


class Solution:
    def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]:
        """
        2657. Find the Prefix Common Array of Two Arrays
        Time: O(n)
        Space: O(n)
        """
        n = len(A)
        seen = [0] * (n + 1)
        answer = []
        common = 0

        for a, b in zip(A, B):
            seen[a] += 1
            if seen[a] == 2:
                common += 1

            seen[b] += 1
            if seen[b] == 2:
                common += 1

            answer.append(common)

        return answer