C++ O(n) Easy Solution with comments, using unordered_map, Suggestions Welcome :)


#1
vector<int> Solution::dNums(vector<int> &A, int B) 
{
    if(B == 0)
    {
        return A;
    }
    vector<int> res;
    int N = A.size();
    if(B > N)
    {
        return res;
    }
    int count, i;
    unordered_map<int, int> mp;
    
    // Initialize counter to 0
    count = 0;
    
    // Add first B elements to window, and check their unique count
    for(i = 0; i < B; i++)
    {
        // If mp[A[i]] == 0 i.e. not found in map or no occurrences, then increment count
        if(mp[A[i]] == 0)
        {
            count++;
        }
        
        // Increment count of occurrences of A[i] in current window
        mp[A[i]]++;
    }
    res.emplace_back(count);
    for(i; i < N; i++)
    {
        // Check if removing the leftmost element from the window
        // Changes the count of distint elements or not
        if(mp[A[i - B]] == 1)
        {
            count--;
        }
        
        // Since leftmost element leaves the window, remove its count
        mp[A[i - B]]--;
        
        // Add the ith element to map, increment count only if unique
        if(mp[A[i]] == 0)
        {
            count++;
        }
        
        mp[A[i]]++;
        res.emplace_back(count);
    }
    return res;
}