তিনটি অ্যারেতে কমন এলিমেন্ট খুঁজতে HashSet<T> এবং IntersectWith বা LINQ Intersect ব্যবহার করা হয়। HashSet O(1) লুকআপ দিয়ে খুব দ্রুত।
পদ্ধতি ১: HashSet IntersectWith (ইন-প্লেস, দ্রুত)
var set1 = new HashSet<int>(arr1);
var set2 = new HashSet<int>(arr2);
var set3 = new HashSet<int>(arr3);
set1.IntersectWith(set2);
set1.IntersectWith(set3);
// set1 এখন তিনों সেটের কমন এলিমেন্ট ধারণ করে
পদ্ধতি ২: LINQ Intersect (চেইনেবল, রিড-অনলি)
var common = arr1.Intersect(arr2).Intersect(arr3);
সম্পূর্ণ উদাহরণ (দুই পদ্ধতিই)
using System;
using System.Collections.Generic;
using System.Linq;
class ThreeArrayCommonDemo
{
public static void Main()
{
int[] arr1 = { 99, 57, 63, 98 };
int[] arr2 = { 43, 99, 33, 57 };
int[] arr3 = { 99, 57, 42 };
// HashSet পদ্ধতি
var h1 = new HashSet<int>(arr1);
var h2 = new HashSet<int>(arr2);
var h3 = new HashSet<int>(arr3);
h1.IntersectWith(h2);
h1.IntersectWith(h3);
Console.WriteLine("HashSet: " + string.Join(", ", h1));
// LINQ পদ্ধতি
var common = arr1.Intersect(arr2).Intersect(arr3);
Console.WriteLine("LINQ: " + string.Join(", ", common));
}
}
আউটপুট
HashSet: 99, 57
LINQ: 99, 57
সর্টেড অ্যারে এর জন্য টু-পয়েন্টার অ্যালগরিদম (O(n), এক্সট্রা স্পেস নেই)
int i = 0, j = 0, k = 0;
while (i < a.Length && j < b.Length && k < c.Length)
{
if (a[i] == b[j] && b[j] == c[k])
{
Console.Write(a[i] + " ");
i++; j++; k++;
}
else if (a[i] < b[j]) i++;
else if (b[j] < c[k]) j++;
else k++;
}
এই পদ্ধতিতে অ্যারেগুলো সর্টেড থাকতে হবে।