Unraveling Uniqueness and Anagram Mysteries with TypeScript Sets

Lesson Introduction

Welcome to our focused exploration of TypeScript's set and its remarkable applications in solving algorithmic challenges. In this lesson, we will dive into how this powerful data structure can be used to tackle specific problems often encountered in technical interviews.

Problem 1: Unique Echo

Picture this: you're given a vast list of words, and you must identify the final word that stands proudly solitary — the last word that is not repeated. Imagine sorting through a database of unique identifiers and finding one identifier towards the end of the list that is unlike any others.

Problem 1: Naive Approach

The straightforward approach would be to examine each word in reverse, comparing it to every other word for uniqueness. This brute-force method would result in poor time complexity, O(n2)O(n^2), which is less than ideal for large datasets.

Problem 1: Efficient Approach

We can use two sets with type annotations: wordsSet to maintain unique words and duplicatesSet to keep track of duplicate words. By the end, we can remove all duplicated words from wordsSet to achieve our goal. Here's how to use a set in TypeScript to solve the problem:

TypeScript
function findLastUniqueWord(words: string[]): string {
    let wordsSet: Set<string> = new Set();
    let duplicatesSet: Set<string> = new Set();

    for (const word of words) {
        if (wordsSet.has(word)) {
            duplicatesSet.add(word);
        } else {
            wordsSet.add(word);
        }
    }

    for (let i = words.length - 1; i >= 0; i--) {
        if (!duplicatesSet.has(words[i])) {
            return words[i];
        }
    }

    return "";
}

Let's dive in to the process step by step:

  1. Initialization: We first initialize two sets: wordsSet to accumulate unique words, and duplicatesSet to store the words that appear more than once.

  2. Iteration: As we iterate through each word in the words array:

    • If wordsSet already contains the word, it is added to duplicatesSet. This helps in identifying duplicates.
    • Otherwise, the word is added to wordsSet.
  3. Finding the Last Unique Word: We loop through the words array in reverse order. The first word that is not found in duplicatesSet during this backward traversal is the last unique word. We immediately return this word as our result.

  4. Return: If no unique word is found (should not happen if input constraints are respected), we return an empty string.

For the example collection ["apple", "banana", "apple", "orange", "kiwi", "banana"], "kiwi" would be returned as the last unique element.

This efficient approach, with a time complexity closer to O(n)O(n), is far superior to the naive method and showcases your proficiency at solving algorithmic problems with TypeScript's set.

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