Remove Element

Problem statement

Delete every instance of val from nums without allocating a new array. Return how many elements remain, and make sure the first that many slots of nums hold those survivors (order among survivors can be any).

Example:

Input:

nums = [3, 2, 2, 3], val = 3

Expected output:

length 2, nums begins [2, 2, ...]

Practice on LeetCode: Remove Element

Golang Solution

func removeElement(nums []int, val int) int {
    j := 0
    for i := 0; i < len(nums); i++ {
        if nums[i] != val {
            nums[j] = nums[i]
            j += 1
        }
    }
    return j
}