Problem Description
Given two 0-indexed integer permutations A and B of length n, compute the prefix common array C such that C[i] is equal to the count of numbers that have appeared at or before index i in both A and B.
Key Insights
- Both A and B are permutations containing all integers from 1 to n.
- As you traverse both arrays, you can keep track of seen elements using sets.
- The count at each index is determined by the intersection of the sets of elements seen so far in A and B.
- Since n is small (up to 50), iterating over the sets to count common elements is efficient.
Space and Time Complexity
Time Complexity: O(n^2) in the worst-case scenario because of the intersection counting at each step, but with n <= 50, this is acceptable. Space Complexity: O(n) for storing seen elements.
Solution
We maintain two sets: one for elements seen in A and one for elements seen in B. For each index i, we add the current element from A to the first set and the current element from B to the second set. Then, we calculate the number of common elements by computing the intersection of these sets. This intersection count is appended to the result array C. This method uses straightforward set operations to determine the common elements at every prefix.