Leetcode 2657: Find the Prefix Common Array of Two Arrays

grid47
grid47
Exploring patterns and algorithms
Feb 15, 2024 7 min read

You are given two integer arrays A and B, each of length n, which are permutations of numbers from 1 to n. You need to find the prefix common array of A and B. The prefix common array is defined as an array C where each C[i] represents the number of integers that appear at or before index i in both A and B.
Problem
Approach
Steps
Complexity
Input: You are given two integer arrays A and B of length n. Both arrays are permutations of integers from 1 to n.
Example: Input: A = [4, 1, 3, 2], B = [2, 1, 4, 3]
Constraints:
• 1 <= A.length == B.length == n <= 50
• 1 <= A[i], B[i] <= n
• A and B are both permutations of integers from 1 to n.
Output: Return the prefix common array, where each element represents the count of common numbers at or before the index i in both arrays A and B.
Example: Output: [0, 1, 2, 3]
Constraints:
• The output should be an array of integers representing the prefix common array.
Goal: The goal is to calculate the prefix common array by checking how many elements from A and B are common up to each index.
Steps:
• Step 1: Iterate through each index of arrays A and B.
• Step 2: Track the common elements up to each index using sets for quick lookup.
• Step 3: Update the prefix common array at each step based on the count of common elements.
Goal: Ensure that the solution works efficiently within the given constraints of n and array sizes.
Steps:
• The arrays A and B are permutations, meaning they contain all integers from 1 to n exactly once.
Assumptions:
• Both arrays A and B contain all integers from 1 to n exactly once.
Input: Input: A = [4, 1, 3, 2], B = [2, 1, 4, 3]
Explanation: At index 0: no numbers are common, so C[0] = 0. At index 1: 1 is common, so C[1] = 1. At index 2: 1 and 4 are common, so C[2] = 2. At index 3: 1, 4, 3, and 2 are common, so C[3] = 4.

Input: Input: A = [5, 2, 4, 1, 3], B = [3, 1, 5, 4, 2]
Explanation: At index 0: no numbers are common, so C[0] = 0. At index 1: only 2 is common, so C[1] = 1. At index 2: 2 and 5 are common, so C[2] = 2. At index 3: 2, 5, and 4 are common, so C[3] = 3. At index 4: all elements are common, so C[4] = 5.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus