Overview
An integer array is given and a target element is given. Remove all occurrences of that target element from the array. The removal must be done in place
Input: [1, 4, 2, 5, 4]
Target: 4
Output: [1, 2, 5]
Input: [1, 2, 3]
Target:3
Output: [1, 2]
Program
Here is the program for the same.
package main
import (
"fmt"
)
func removeElement(nums []int, val int) []int {
lenNums := len(nums)
k := 0
for i := 0; i < lenNums; {
if nums[i] != val {
nums[k] = nums[i]
k++
}
i++
}
return nums[0:k]
}
func main() {
output := removeElement([]int{1, 4, 2, 5, 4}, 4)
fmt.Println(output)
output = removeElement([]int{1, 2, 3}, 3)
fmt.Println(output)
}
Output
[1 2 5]
[1 2]