2657. Find the Prefix Common Array of Two Arrays #1142
-
Topics: You are given two 0-indexed integer permutations A prefix common array of Return the prefix common array of A sequence of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can iterate over the two arrays A and B while keeping track of the numbers that have occurred at or before the current index in both arrays. Since both arrays are permutations of the same set of numbers, we can utilize two hash sets (or arrays) to store which numbers have appeared at or before the current index in both arrays. For each index, we can count the common numbers that have appeared in both arrays up to that point. Solution Approach:
Let's implement this solution in PHP: 2657. Find the Prefix Common Array of Two Arrays <?php
/**
* @param Integer[] $A
* @param Integer[] $B
* @return Integer[]
*/
function findThePrefixCommonArray($A, $B) {
$n = count($A); // Length of arrays
$freqA = array_fill(0, $n + 1, 0); // Frequency array for A
$freqB = array_fill(0, $n + 1, 0); // Frequency array for B
$result = [];
// Iterate through each index and calculate the common count
for ($i = 0; $i < $n; $i++) {
// Increment frequency of A[i] and B[i]
$freqA[$A[$i]]++;
$freqB[$B[$i]]++;
// Count how many elements have appeared in both arrays till this point
$commonCount = 0;
for ($j = 1; $j <= $n; $j++) {
if ($freqA[$j] > 0 && $freqB[$j] > 0) {
$commonCount++;
}
}
// Store the common count in the result array
$result[] = $commonCount;
}
return $result;
}
// Example usage:
$A = [1, 3, 2, 4];
$B = [3, 1, 2, 4];
print_r(findThePrefixCommonArray($A, $B)); // Output: [0, 2, 3, 4]
$A = [2, 3, 1];
$B = [3, 1, 2];
print_r(findThePrefixCommonArray($A, $B)); // Output: [0, 1, 3]
?> Explanation:
Example Walkthrough:For the input: $A = [1, 3, 2, 4];
$B = [3, 1, 2, 4];
Output: Time Complexity:
This should work within the given constraints effectively. |
Beta Was this translation helpful? Give feedback.
We can iterate over the two arrays A and B while keeping track of the numbers that have occurred at or before the current index in both arrays. Since both arrays are permutations of the same set of numbers, we can utilize two hash sets (or arrays) to store which numbers have appeared at or before the current index in both arrays. For each index, we can count the common numbers that have appeared in both arrays up to that point.
Solution Approach:
A
andB
up to indexi
.i
, check if bothA[i]
andB[i]
have been seen before. If so, increment the common count.