Find the Prefix Common Array of Two Arrays — LeetCode 2657 Python Solution

MediumBit ManipulationArrayHash Table
Problem
#2657
Reading time
2 min

The problem

You are given two 0-indexed integer permutations A and B of length n. A prefix common array of A and B is an array C such that C[i] is equal to the count of numbers that are present at or before the index i in both A and B.

Example

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.

Python solution

Python
class Solution:
    def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]:
        ans = []
        cnt1 = Counter()
        cnt2 = Counter()
        for a, b in zip(A, B):
            cnt1[a] += 1
            cnt2[b] += 1
            t = sum(min(v, cnt2[x]) for x, v in cnt1.items())
            ans.append(t)
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2657. Find the Prefix Common Array of Two Arrays is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2657. Find the Prefix Common Array of Two Arrays?
LeetCode 2657. Find the Prefix Common Array of Two Arrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 2657. Find the Prefix Common Array of Two Arrays?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2657. Find the Prefix Common Array of Two Arrays?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2657. Find the Prefix Common Array of Two Arrays cover?
LeetCode 2657. Find the Prefix Common Array of Two Arrays is tagged Bit Manipulation, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview