2657. Find the Prefix Common Array of Two Arrays
MediumView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Intuition
Find the k closest numbers using a two-pointer approach on sorted array or priority queue.
Algorithm
- 1Sort. Binary search for insertion point of target. Two pointers expanding outward. Take k closest.
Common Pitfalls
- •Tie-breaking: prefer smaller element. Two pointers from found position outward.
2657.cs
C#
// Approach: Track seen elements from A and B using sets; count overlap at each index.
// Time: O(n) Space: O(n)
public class Solution
{
public int[] FindThePrefixCommonArray(int[] A, int[] B)
{
int[] commonArray = new int[A.Length];
int commonNos = 0;
for (int i = 0; i < A.Length; i++)
{
commonNos = 0;
for (int j = 0; j <= i; j++)
{
for (int k = 0; k <= i; k++)
{
if (A[j] == B[k])
{
commonNos++;
}
}
}
Console.WriteLine("Common numbers: " + commonNos);
commonArray[i] = commonNos;
}
return commonArray;
}
}Advertisement
Was this solution helpful?