Search⌘ K

Solution Review: Check if Arrays are Disjoint

Explore how to verify if two arrays are disjoint by using a HashSet in C#. Understand the basic hashing technique to achieve efficient lookups and minimize time complexity, essential for coding interviews.

We'll cover the following...

Solution: Use a HashSet

C#
using System;
using System.Collections.Generic;
namespace chapter_9
{
class challenge_2
{
static bool isDisjoint(int [] arr1, int [] arr2, int size1, int size2)
{
//Create a HashSet and store all values of arr1 in it
HashSet<int> ht = new HashSet<int>(); ;
// ht stores all the values of arr1
for (int i = 0; i < size1; i++)
{
if (!ht.Contains(arr1[i]))
ht.Add(arr1[i]);
}
for (int i = 0; i < size2; i++)
{
if (ht.Contains(arr2[i]))
return false;
}
return true;
}
static void Main(string[] args)
{
int [] arr1 = { 9, 4, 3, 1, -2, 6, 5 };
int [] arr2 = { 7, 10, 8 };
Console.WriteLine(isDisjoint(arr1, arr2, 7, 3));
return;
}
}
}

There is nothing tricky going on here. The problem is similar to the previous one. All you have to do is create a hash table for arr1 and as soon as you find any value from arr2 in the hash table, you can conclude that the two arrays are not disjoint.

Time complexity

For a lookup array with ...