#2657
Find the Prefix Common Array of Two Arrays
MediumArrayHash TableBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a frequency array to track the occurrences of numbers seen so far in both arrays. This allows us to count common elements efficiently without nested loops.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty array C of the same length as A and B.
- 2Step 2: Initialize a frequency array of size n+1 to count occurrences of numbers in A and B.
- 3Step 3: For each index i from 0 to n-1, increment the frequency of A[i] and B[i].
- 4Step 4: Count how many numbers have been seen in both arrays up to index i and store that in C[i].
- 5Step 5: Return the array C.
solution.py14 lines
1# Full working Python code
2
3def findPrefixCommonArray(A, B):
4 n = len(A)
5 C = [0] * n
6 freq = [0] * (n + 1)
7 for i in range(n):
8 freq[A[i]] += 1
9 freq[B[i]] += 1
10 C[i] = sum(1 for count in freq if count > 1)
11 return C
12
13# Example usage
14print(findPrefixCommonArray([1,3,2,4], [3,1,2,4]))ℹ
Complexity note: The time complexity is O(n) because we iterate through the arrays once, and the space complexity is O(n) due to the frequency array used to track occurrences.
- 1Both arrays are permutations, so every number from 1 to n appears exactly once.
- 2Counting occurrences efficiently allows us to determine common elements without nested loops.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.