Leetcode – Remove Element

Name: Remove Element
Difficulty: Easy
Description: Remove all instances of val from nums, modify in place, return new count.

Example:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
After count (5 in this case), the rest of the nums are ignored.

This is a simple solution, the idea is to have two indexes. The first (i) iterates over nums, the second (index) only advances when the dereferenced i is not equal to the specified val.

int removeElement(vector<int>& nums, int val) {
    if (nums.empty()) return 0;
    if (nums.size() == 1) return nums.front() == val ? 0 : 1;

    auto index = nums.begin();

    for(auto i = index; i < nums.end(); ++i) {
        if (*i != val) {
            *index++ = *i;
        }
    }

    return static_cast<int>(index - nums.begin());
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s