Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Remove all occurrences of a given value in an array in place

Posted on January 31, 2022January 31, 2022 by admin

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]
©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme