Problems

#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;

    }
};

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;
    }
};

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 {};
    }
};

#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;
    }
};

Last updated

Was this helpful?