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
Problem 1: Efficient Solution Building
Problem 1: Time complexity
Problem 2: Remove Duplicates in an Array

Now, we move on to a common data-cleaning problem: removing duplicates from an array. Just like a librarian cataloging books, duplicates waste space and cause confusion. We want our array to contain unique entries.

Problem 2: Approaches
Problem 2: Solution Building

Let's apply this in code:

  1. First, we create a set from our array, serving as an assistant that automatically filters out duplicate names from our lists.
  2. Then, we convert our set, now containing unique names, back into an array, ready for use.
// Defining the removeDuplicates function
function removeDuplicates<T>(array: T[]): T[] {
  return Array.from(new Set(array));
}

console.log(removeDuplicates(['apple', 'apple', 'banana', 'banana', 'cherry'])); // ['apple', 'banana', 'cherry']
console.log(removeDuplicates([1, 5, 3, 5, 2, 2, 1])); // [1, 5, 3, 2]

These examples demonstrate how sets elegantly handle duplicate removal, producing arrays that succinctly represent the unique elements they originally contained.

Problem 2: Time complexity
Lesson Summary

In today's lesson, we've reinforced the power of TypeScript sets for solving common algorithmic problems efficiently while leveraging type safety. We explored how sets can be used in scenarios like ensuring disjointness and eliminating duplicates, underscoring their versatility in TypeScript. Let's continue to the practice exercises to witness these concepts in action!

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