> For the complete documentation index, see [llms.txt](https://dsa-cpp.gitbook.io/nafees/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dsa-cpp.gitbook.io/nafees/hash-table/problems.md).

# Problems

## Q1: [Ransom Note](https://leetcode.com/problems/ransom-note/)

```cpp
#include <unordered_map>

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> mp;
        for(int i = 0; i < magazine.size(); i++) {
            if(mp.find(magazine[i]) != mp.end()) mp[magazine[i]]++;
            else mp[magazine[i]] = 1;
        }
        for(int i = 0; i < ransomNote.size(); i++) {
            if(mp.find(ransomNote[i]) != mp.end() && mp[ransomNote[i]] > 0)
                mp[ransomNote[i]]--;
            else
                return false;
        }
        return true;

    }
};
```

## Q2:  [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)

```cpp
class Solution {
public:
    
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> mp;
        for(int i = 0; i < nums.size(); i++) {
            if(mp.find(nums[i]) != mp.end() && (i+1 - mp[nums[i]]) <= k) return true;
            mp[nums[i]] = i+1;  
        }
        return false;
    }
};
```

## Q3: [Two Sum](https://leetcode.com/problems/two-sum/)

```cpp
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> mp;
        for(int i = 0; i < nums.size(); i++) {
            for(int j = 0; j < i; j++) {
                if(mp.find(j) != mp.end()  && mp[j] + nums[i] == target)
                    return {i, j};
            }
            mp[i] = nums[i];  
        }
        return {};
    }
};
```

## Q4: [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)

```cpp
#include <unordered_map>
class Solution {
public:
    static bool compare(pair<int,int>& a, pair<int,int>& b) {
        return a.first > b.first;
    }
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> mp;
        int count = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(mp.find(nums[i]) != mp.end())
                mp[nums[i]]++;
            else {
                mp[nums[i]] = 1;
                count++;
            }
        }
        
        vector<pair<int, int>> temp(count);
        temp.clear();

        for(auto it = mp.begin(); it != mp.end(); it++) {
            temp.push_back({it->second, it->first});
        }
        
        sort(temp.begin(), temp.end(), compare);
        
        vector<int> res(k);
        res.clear();

        for(int i= 0; i < k; i++) {
            res.push_back(temp[i].second);
        }
        return res;
    }
};
```
