C++ Online Compiler
Example: Hash Map Duplicate Finder in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Hash Map Duplicate Finder #include <iostream> #include <vector> #include <unordered_set> // For std::unordered_set int findDuplicateHashMap(const std::vector<int>& nums) { // Step 1: Create an unordered set to store unique numbers encountered std::unordered_set<int> seen_numbers; // Step 2: Iterate through the input numbers for (int num : nums) { // Step 3: Check if the number is already in the set if (seen_numbers.count(num)) { // Step 4: If yes, it's a duplicate return num; } // Step 5: If not, add it to the set seen_numbers.insert(num); } // Step 6: Should not be reached under problem constraints return -1; } int main() { std::vector<int> nums = {1, 3, 4, 2, 2}; int duplicate = findDuplicateHashMap(nums); if (duplicate != -1) { std::cout << "The duplicate number is: " << duplicate << std::endl; } else { std::cout << "No duplicate found." << std::endl; } std::vector<int> nums2 = {3, 1, 3, 4, 2}; duplicate = findDuplicateHashMap(nums2); if (duplicate != -1) { std::cout << "The duplicate number is: " << duplicate << std::endl; } else { std::cout << "No duplicate found." << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS