'Remove all occurrences of the same element from slice

I have the following code:

func TestRemoveElement(t *testing.T) {
    nums := []int{3, 2, 2, 3}
    result := removeElement(nums, 3)

    if result != 2 {
        t.Errorf("Expected 2, but it was %d instead.", result)
    }
}

func removeElement(nums []int, val int) int {

    for i, v := range nums {
        if v == val {
            nums = append(nums[:i], nums[i+1:]...)
        }
    }
    return len(nums)
}

The statement inside the if statement is the most popular way of replacing an element in a slice per this answer. But this fails deleting the last element due to i+1. i.e if a match is found in the last element, i+1 is out of bounds. What better way to replace elements that considers last elements?



Solution 1:[1]

It looks like you are trying to remove all elements equal to val. One way to do this is to copy values not equal to val to the beginning of the slice:

func removeElement(nums []int, val int) []int {
    j := 0
    for _, v := range nums {
        if v != val {
            nums[j] = v
            j++
        }
    }
    return nums[:j]
}

Return the new slice instead of returning the length. It will be more convenient for the caller.

If you only want to remove the first element equal to val, then use this code:

func removeElement(nums []int, val int) []int {
    for i, v := range nums {
        if v == val {
            return append(nums[:i], nums[i+1:]...)
        }
    }
    return nums
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1