Introduction

Welcome to our focused exploration of C++'s std::unordered_set and its remarkable applications in solving algorithmic challenges. In this lesson, "Mastering Unique Elements and Anagram Detection with C++ std::unordered_set," we'll delve into how this efficient data structure can be leveraged to address and solve various types of problems commonly 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 other.

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(n^2), which is less than ideal for large datasets.

Here is the naive approach in C++:

#include <vector>
#include <string>

std::string FindLastUniqueWordNaive(const std::vector<std::string>& words)
{
    for (int i = words.size() - 1; i >= 0; i--)
    {
        bool isUnique = true;
        for (int j = 0; j < words.size(); j++)
        {
            if (i != j && words[i] == words[j])
            {
                isUnique = false;
                break;
            }
        }
        
        if (isUnique)
        {
            return words[i];
        }
    }

    return ""; // In case no unique word is found
}

As you might notice, the naive solution checks each word against every other word, leading to a time complexity of O(n^2) due to the nested loops. For each word, you perform n comparisons with the remaining words in the list.

Efficient Approach

We can utilize two std::unordered_set<std::string> instances: 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.

Create a std::unordered_set instance to store unique words:

#include <unordered_set>

std::unordered_set<std::string> wordsSet;

Initialize another std::unordered_set to monitor duplicates:

std::unordered_set<std::string> duplicatesSet;

Iterate through the word list, filling wordsSet and duplicatesSet:

for (const auto& word : words)
{
    if (wordsSet.find(word) != wordsSet.end())
    {
        duplicatesSet.insert(word);
    }
    else
    {
        wordsSet.insert(word);
    }
}

Manually remove all duplicated words from wordsSet:

for (const auto& dup : duplicatesSet)
{
    wordsSet.erase(dup);
}

Now, wordsSet only contains unique words. Find the last unique word by iterating through the original word list from the end:

std::string lastUniqueWord = "";
for (int i = words.size() - 1; i >= 0; i--)
{
   if (wordsSet.find(words[i]) != wordsSet.end())
   {
       lastUniqueWord = words[i];
       break;
   }
}

Full code:

#include <vector>
#include <string>
#include <unordered_set>

std::string FindLastUniqueWordEfficient(const std::vector<std::string>& words)
{
    std::unordered_set<std::string> wordsSet;
    std::unordered_set<std::string> duplicatesSet;

    for (const auto& word : words)
    {
        if (wordsSet.find(word) != wordsSet.end())
        {
            duplicatesSet.insert(word);
        }
        else
        {
            wordsSet.insert(word);
        }
    }

    for (const auto& dup : duplicatesSet)
    {
        wordsSet.erase(dup);
    }

    std::string lastUniqueWord = "";
    for (int i = words.size() - 1; i >= 0; i--)
    {
       if (wordsSet.find(words[i]) != wordsSet.end())
       {
           lastUniqueWord = words[i];
           break;
       }
    }

    return lastUniqueWord;
}

This efficient approach, with a time complexity close to O(n), is far superior to the naive method and showcases your proficiency in solving algorithmic problems with C++'s std::unordered_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