An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Hello @Naji Afache ,
Thanks for your question.
The current code is O(n²) - with 190k items that's completely infeasible. Even if each array is tiny, you're doing ~36 trillion comparisons.
Since you only care about ≥ 2 common elements, index every possible pair of numbers. Any two arrays that share the same pair automatically have intersection ≥ 2. This reduces the problem dramatically if your arrays are reasonably small.
using System;
using System.Collections.Generic;
using System.Linq;
public class ArrayGroupAnalyzer
{
public List<int[]> FindArraysWithSharedPairs(List<int[]> arrayGroup)
{
if (arrayGroup == null || arrayGroup.Count < 2)
return new List<int[]>();
var resultSet = new HashSet<int>();
var pairIndex = new Dictionary<(int, int), List<int>>(capacity: arrayGroup.Count * 20);
for (int i = 0; i < arrayGroup.Count; i++)
{
var arr = arrayGroup[i];
if (arr == null || arr.Length < 2) continue;
var seen = new HashSet<int>(arr);
var sorted = seen.ToArray();
Array.Sort(sorted);
for (int a = 0; a < sorted.Length; a++)
{
for (int b = a + 1; b < sorted.Length; b++)
{
var pair = (sorted[a], sorted[b]);
if (!pairIndex.TryGetValue(pair, out var list))
{
list = new List<int>(4);
pairIndex[pair] = list;
}
list.Add(i);
}
}
}
foreach (var kvp in pairIndex)
{
var indices = kvp.Value;
if (indices.Count >= 2)
{
foreach (var idx in indices)
{
resultSet.Add(idx);
}
}
}
return resultSet
.OrderBy(idx => idx)
.Select(idx => arrayGroup[idx])
.ToList();
}
}
I hope this addresses your question. If this response was helpful, please consider following the guidance to provide feedback.