Exploring Sets in TypeScript: Ensuring Uniqueness and Optimizing Performance

Introduction to the Lesson

Today, we will tackle two problems demonstrating how TypeScript sets can streamline your code and optimize performance. TypeScript offers additional benefits, such as type safety, when handling collections of unique items. This makes sets the ideal data structure for solving uniqueness and membership testing problems while ensuring all items adhere to specified types.

Problem 1: Check if Two Sets are Disjoint

Let's begin by considering the function areDisjoint, which takes two arrays and determines if they are disjoint, meaning they have no elements in common. This is crucial when analyzing datasets for overlapping values, similar to ensuring that two puzzle pieces from different puzzles don't fit together.

Imagine two companies looking to cross-promote products but wishing to target customers who have yet to interact with both brands. Ensuring that their promotional efforts are disjoint becomes essential.

Problem 1: Naive Approach

A naive approach would be to iterate over every element in the first array and, for each one, check every element in the second array for a match. This can be inefficient for larger datasets, making this method prohibitive due to its time complexity of O(nâ‹…m)O(n \cdot m).

Problem 1: Efficient Solution Building

Consider a scenario with a list of names and a super-fast scanner that can immediately tell you whether a name is on the list. In TypeScript terms, this is what sets offer via their has method — a way to check presence in constant time, O(1)O(1).

We can also check if an element has some matches for a given condition with the some method, which has a time complexity of O(n)O(n).

Let's build the solution, with this analogy in mind, step by step:

  1. Transfer the elements of one array into our super-fast scanner, a.k.a. a set called set1.
  2. Feed names from the other array to the scanner using the .some() method to check if set1 can find a match.
  3. Since we want to determine whether there are no twins (common elements), we invert the result of .some() because it returns true if it finds at least one match.
TypeScript
// Defining the function areDisjoint
function areDisjoint<T>(array1: T[], array2: T[]): boolean {
  const set1 = new Set(array1);
  return !array2.some(element => set1.has(element));
}

// Example calls to the function, highlighting the differences in arrays
console.log(areDisjoint(['Alice', 'Bob', 'Charlie'], ['Xander', 'Yasmine', 'Zane'])); // true, no common names
console.log(areDisjoint(['Alice', 'Bob', 'Charlie'], ['Charlie', 'Delta', 'Echo'])); // false, 'Charlie' is common to both

This code illustrates how sets can quickly indicate whether two lists share elements, producing true for completely disjoint lists and false otherwise.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal