Find the Prefix Common Array of Two Arrays — LeetCode 2657 Python Solution
- Problem
- #2657
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(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.