DEV Community

Discussion on: Daily Challenge #237 - Delete Extra Occurrences

Collapse
 
vidit1999 profile image
Vidit Sarkar

Here is C++ solution,

vector<int> delete_nth(vector<int> arr, int occ){
    // stores the numbers and its corresponding count in answer vector
    unordered_map<int, int> numCount;
    // the answer vector
    vector<int> ans;

    // if count of any number is less than occ,
    // only then add it in ans
    for(int num : arr){
        if(numCount[num] < occ){
            ans.push_back(num);
            numCount[num]++;
        }
    }

    return ans;
}
Collapse
 
arjunjv profile image
sai kiran jv

What if given numbers are not positive ?

Collapse
 
vidit1999 profile image
Vidit Sarkar

ans vector contains each number only up to occ times. So, occ can never be negative. If user passed a negative number as occ, then ans vector will be empty.

If given numbers are negative, still there should not be any problem. Example,

delete_nth({-1,-1,-1,-2,-3,-2,-4,-3}, 1)  => {-1,-2,-3,-4}
delete_nth({1,-2,3,-7,-2,3,-8},1)  => {1,-2,3,-7,-8}