Welcome back! Today, we're sharpening our algorithmic problem-solving skills, focusing on std::unordered_map
in C++. Imagine std::unordered_map
as the backbone of a social network app, ensuring that each user's data remains unique and instantly accessible. By the close of this lesson, you will be equipped to use C++'s std::unordered_map
to efficiently solve problems that might otherwise seem daunting due to their complexity or data size.
Our journey begins with the Majority Element Finder. You're handed an array of integers, and your mission is simple yet intriguing: determine whether this array has a celebrity element. This integer appears more frequently than all others combined. More formally, we are looking for an element appearing more than n/2
times.
Why does this matter? Well, consider analyzing sales data to determine the most sold product in an online marketplace — knowing the majority of products could streamline marketing strategies and inventory management. That's the real-world relevance of the majority element problem.
Now, let's be savvy about this. Enter the std::unordered_map
: your sophisticated voting tally system. With it, you can keep a running total of each product's sales as you go through the transaction list once rather than reviewing the entire list for each product. It grants us the speed of an experienced cashier who knows customers' habits by heart.
Let's dissect the process in our election analogy step by step:
C++1#include <unordered_map> 2#include <vector> 3 4int FindMajorityElement(const std::vector<int>& arr) { 5 std::unordered_map<int, int> countMap; 6 int majorityThreshold = arr.size() / 2;
Here, we're preparing our std::unordered_map
, akin to setting up our ballot boxes and establishing the majority threshold — the number of votes needed to win the election by a landslide.
C++1 for (const auto& num : arr) { 2 countMap[num] += 1;
We're recording every vote cast in our std::unordered_map
ledger. Each key is a unique product, and the value is the current total of received votes.
C++1 if (countMap[num] > majorityThreshold) { 2 return num; 3 } 4 }
Once a product's vote count exceeds the threshold — signaling a majority — our search concludes, akin to declaring a winner!
C++1#include <unordered_map> 2#include <vector> 3 4int FindMajorityElement(const std::vector<int>& arr) { 5 std::unordered_map<int, int> countMap; 6 int majorityThreshold = arr.size() / 2; 7 8 for (const auto& num : arr) { 9 countMap[num] += 1; 10 11 if (countMap[num] > majorityThreshold) { 12 return num; 13 } 14 } 15 16 return -1; // No majority element found 17}
If the polling ends with no majority victor, we return -1
, signifying a contested market where no single product dominates.
Imagine you are building a search feature for an app, and you need a function that quickly retrieves all documents where a certain keyword is present. If you have ever searched for something using your browser's Ctrl+F
or Command+F
function, you have utilized such an index! Our task is to create an unordered map that behaves like an index, mapping a keyword to all the documents where it can be found.
This capability is the cornerstone of search engines or reference databases — offering instant results when you look up a word or phrase. Indexing is an unsung hero in big data, where speed is invaluable.
Our std::unordered_map
steps in as our digital librarian, capable of cataloging every word and its locations at a fantastic clip. It's the magic behind the fast search results we often take for granted.
Let's delve into our code, assembling our digital index:
C++1#include <iostream> 2#include <sstream> 3#include <unordered_map> 4#include <vector> 5#include <string> 6 7std::unordered_map<std::string, std::vector<int>> CreateKeywordIndex(const std::vector<std::string>& docs) { 8 std::unordered_map<std::string, std::vector<int>> index;
This line can be likened to opening a new spreadsheet where each row represents a distinct word, and the columns list the document numbers where the word appears.
C++1 for (int i = 0; i < docs.size(); ++i) { 2 std::istringstream iss(docs[i]); 3 std::string word; 4 while (iss >> word) {
Here, we're flipping through each document and dissecting it into individual words. It's parallel to scanning each page of our metaphorical book.
C++1#include <iostream> 2#include <sstream> 3#include <unordered_map> 4#include <vector> 5#include <string> 6 7std::unordered_map<std::string, std::vector<int>> CreateKeywordIndex(const std::vector<std::string>& docs) { 8 std::unordered_map<std::string, std::vector<int>> index; 9 10 for (int i = 0; i < docs.size(); ++i) { 11 std::istringstream iss(docs[i]); 12 std::string word; 13 while (iss >> word) { 14 if (!word.empty()) { 15 index[word].push_back(i); 16 } 17 } 18 } 19 20 return index; 21}
For every word we encounter, we pinpoint its listing or create one if it's new. Then, we're cross-referencing the document index, much like jotting down on which page a topic is discussed.
To wrap up, we've tackled two distinctive algorithmic interview problems, employing std::unordered_map
to our advantage. From deducing the majority winner among a sea of data to compiling a comprehensive keyword index, you now glimpse the robustness and efficiency that std::unordered_map
brings. It's time to roll up your sleeves as we transition from theory to hands-on practice!