Skip to content

Commit 3d2c595

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.8 MB (32.03%)
1 parent 3d97069 commit 3d2c595

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>You are given two <strong>0-indexed </strong>integer<strong> </strong>permutations <code>A</code> and <code>B</code> of length <code>n</code>.</p>
2+
3+
<p>A <strong>prefix common array</strong> of <code>A</code> and <code>B</code> is an array <code>C</code> such that <code>C[i]</code> is equal to the count of numbers that are present at or before the index <code>i</code> in both <code>A</code> and <code>B</code>.</p>
4+
5+
<p>Return <em>the <strong>prefix common array</strong> of </em><code>A</code><em> and </em><code>B</code>.</p>
6+
7+
<p>A sequence of <code>n</code> integers is called a&nbsp;<strong>permutation</strong> if it contains all integers from <code>1</code> to <code>n</code> exactly once.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> A = [1,3,2,4], B = [3,1,2,4]
14+
<strong>Output:</strong> [0,2,3,4]
15+
<strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0.
16+
At i = 1: 1 and 3 are common in A and B, so C[1] = 2.
17+
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
18+
At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4.
19+
</pre>
20+
21+
<p><strong class="example">Example 2:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> A = [2,3,1], B = [3,1,2]
25+
<strong>Output:</strong> [0,1,3]
26+
<strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0.
27+
At i = 1: only 3 is common in A and B, so C[1] = 1.
28+
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
29+
</pre>
30+
31+
<p>&nbsp;</p>
32+
<p><strong>Constraints:</strong></p>
33+
34+
<ul>
35+
<li><code>1 &lt;= A.length == B.length == n &lt;= 50</code></li>
36+
<li><code>1 &lt;= A[i], B[i] &lt;= n</code></li>
37+
<li><code>It is guaranteed that A and B are both a permutation of n integers.</code></li>
38+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach 3: Single Pass with Frequency Array
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]:
8+
n = len(A)
9+
prefix_common_array = [0 for _ in range(n)]
10+
freq = [0 for _ in range(n + 1)]
11+
common_count = 0
12+
13+
for current_idx in range(n):
14+
freq[A[current_idx]] += 1
15+
if freq[A[current_idx]] == 2:
16+
common_count += 1
17+
18+
freq[B[current_idx]] += 1
19+
if freq[B[current_idx]] == 2:
20+
common_count += 1
21+
22+
prefix_common_array[current_idx] = common_count
23+
24+
return prefix_common_array

0 commit comments

Comments
 (0)